2012-12-03 46 views
1

假设我有一组数据,并且想要为每个与它一起绘制的几何图形添加一个图例。例如:如何在ggplot2中添加几何图例?

x <- rnorm(100, 1) 
qplot(x = x, y = 1:100, geom = c("point", "smooth")) 

而且它会是这个样子:

enter image description here

现在,我想补充一个传奇所以会这样说:

Legend title 
* points [in black] 
--- smoothed [in blue] 

在哪里我指定了“传奇头衔”,“点数”和“平滑”名字。

我该怎么办?

回答

2

添加额外信息的最简单方法是使用注释而不是图例。 (我知道这是一个玩具的例子,但ggplot是明智的,因为只有一种点和一种线的时候,不包括图例,你可以创造一个图例,但它默认会占用更多的空间和墨水而不是必要的,并且需要更多的工作,当只有一种点时,它的含义应该从x和y轴上的标签以及图的一般上下文中清楚地表明,缺少其他信息,读者会推断这条线是对点的函数拟合的结果,他们唯一不知道的是灰色误差区域的具体函数和含义,可以是一个简单的标题,注释,或图形外的文本。

#Sample data in a dataframe since that works best with ggplot 
set.seed(13013) 
testdf <- data.frame(x <- rnorm(100, 1),y <- 1:100) 

一种选择是一个标题:

ggplot(testdf , aes(x = x, y = y)) + geom_point()+ 
    stat_smooth(method="loess")+ 
    xlab("buckshot hole distance(from sign edge)")+ 
    ylab("speed of car (mph)")+ 
    ggtitle("Individual Points fit with LOESS (± 1 SD)") 

sample ggplot with title

另一种选择是一个注释层。在这里,我使用均值和最大值函数来猜测文本的合理位置,但是可以使用实际数据做得更好,并且可以使用像size=3这样的参数来缩小文本大小。

ggplot(testdf , aes(x = x, y = y)) + geom_point()+ 
    stat_smooth(method="loess")+ 
    xlab("buckshot hole distance (from sign edge)")+ 
    ylab("speed of car (mph)")+ 
    annotate("text", x = max(testdf$x)-1, y = mean(testdf$y), 
    label = "LOESS fit with 68% CI region", colour="blue") 

sample ggplot with annotation

+0

谢谢你的解决方法。不过,我确实需要一个传奇。这是一个非常基本的要求,我很惊讶像ggplot2这样的复杂软件包无法处理它。 – J4y

1

的一个快速方法来标注ggplot情节,就是用geom_text

x <- rnorm(100, 1) 
y = 1:100 
library(ggplot2) 
dat <- data.frame(x=x,y=y) 
bp <- ggplot(data =dat,aes(x = x, y = y))+ 
     geom_point()+ geom_smooth(group=1) 


bp <- bp +geom_text(x = -1, y = 3, label = "* points ", parse=F) 
bp <- bp +geom_text(x = -1, y = -1, label = "--- smoothed ", parse=F,color='blue') 
bp 

enter image description here

+0

感谢您的尝试。 +1,因为我可以用这种方式创建一个临时图例。我会等待,看看有没有人知道如何做出正确的传说。 – J4y