【问题标题】:Add a horizontal line to plot and legend in ggplot2在ggplot2中添加一条水平线来绘制和图例
【发布时间】:2023-03-07 03:08:01
【问题描述】:

此代码创建了一个不错的图,但我想在 y=50 处添加一条水平黑线,并让图例显示一条黑线,图例中的文本为“cutoff”,但在图例中为源留点.我可以用 geom_line 添加线,但无法在图例中获取线。

    library(ggplot2)
    the.data <- read.table( header=TRUE, sep=",", 
    text="source,year,value
    S1,1976,56.98
    S1,1977,55.26
    S1,1978,68.83
    S1,1979,59.70
    S1,1980,57.58
    S1,1981,61.54
    S1,1982,48.65
    S1,1983,53.45
    S1,1984,45.95
    S1,1985,51.95
    S1,1986,51.85
    S1,1987,54.55
    S1,1988,51.61
    S1,1989,52.24
    S1,1990,49.28
    S1,1991,57.33
    S1,1992,51.28
    S1,1993,55.07
    S1,1994,50.88
    S2,1993,54.90
    S2,1994,51.20
    S2,1995,52.10
    S2,1996,51.40
    S3,2002,57.95
    S3,2003,47.95
    S3,2004,48.15
    S3,2005,37.80
    S3,2006,56.96
    S3,2007,48.91
    S3,2008,44.00
    S3,2009,45.35
    S3,2010,49.40
    S3,2011,51.19") 
    ggplot(the.data, aes( x = year, y = value ) ) + 
        geom_point(aes(colour = source)) + 
        geom_smooth(aes(group = 1))

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    (1) 试试这个:

    cutoff <- data.frame( x = c(-Inf, Inf), y = 50, cutoff = factor(50) )
    ggplot(the.data, aes( year, value ) ) + 
            geom_point(aes( colour = source )) + 
            geom_smooth(aes( group = 1 )) + 
            geom_line(aes( x, y, linetype = cutoff ), cutoff)
    

    (2) 关于您的评论,如果您不希望将分界线列为单独的图例,则只需在图上标记分界线会更容易:

    ggplot(the.data, aes( year, value ) ) + 
        geom_point(aes( colour = source )) + 
        geom_smooth(aes( group = 1 )) + 
        geom_hline(yintercept = 50) + 
        annotate("text", min(the.data$year), 50, vjust = -1, label = "Cutoff")
    

    更新

    这似乎更好,并且可以推广到多行,如图所示:

    line.data <- data.frame(yintercept = c(50, 60), Lines = c("lower", "upper"))
    ggplot(the.data, aes( year, value ) ) + 
            geom_point(aes( colour = source )) + 
            geom_smooth(aes( group = 1 )) + 
            geom_hline(aes(yintercept = yintercept, linetype = Lines), line.data)
    

    【讨论】:

    • 我尝试直接在绘图上添加文本,但在我的 Linux 机器上编译时,与绘图的其余部分相比,字体看起来不太好。我现在将使用单独的图例。谢谢
    • 请注意,可以在geom_text 中指定fontface=family=。请参阅?geom_text 底部的示例。
    【解决方案2】:

    另一种解决方案:

    gg <- ggplot(the.data, aes( x = year, y = value ) ) + 
            geom_point(aes(colour = source)) + 
            geom_smooth(aes(group = 1))
    
    cutoff <- data.frame(yintercept=50, cutoff=factor(50))
    gg + 
      geom_hline(aes(yintercept=yintercept, linetype=cutoff), data=cutoff, show_guide=TRUE) 
    

    此代码生成的图形与@G 的点 (1) 中的图形完全相同。格洛腾迪克。但更容易适应多层图形。

    【讨论】:

    • show_guide 已被弃用,请改用show.legend
    猜你喜欢
    • 2019-08-15
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    相关资源
    最近更新 更多