在 ggplot2 中添加水平线和图例

42

这段代码生成了一个漂亮的图,但我想在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))
2个回答

73

(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")

screenshot

更新

这似乎更好,适用于多行,如下所示:

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机器上编译时,字体与图表的其余部分相比不太好看。现在我将使用单独的图例。谢谢。 - Greg
1
请注意,在geom_text中可以指定fontface=family=。请参见?geom_text底部的示例。 - G. Grothendieck

15

另一个解决方案:

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.Grothendieck第1点中的图形完全相同,但更容易适应具有多个图层的图形。


2
show_guide已被弃用,请使用show.legend代替。 - Zhanxiong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接