R 如何在ggplot2中添加几何图形图例?

R 如何在ggplot2中添加几何图形图例?,r,graphics,ggplot2,R,Graphics,Ggplot2,假设我有一组数据,我想给我绘制的每个几何体添加一个图例。例如: x <- rnorm(100, 1) qplot(x = x, y = 1:100, geom = c("point", "smooth")) 其中我指定了“图例标题”、“点”和“平滑”名称 我该怎么做呢?添加额外信息的最简单方法是使用注释而不是图例 (我知道这是一个玩具示例,但ggplot在只有一种点和一种线的情况下不包括图例是明智的。您可以创建图例,但默认情况下,它会占用更多的空间和墨水,并且需要更多的工作。当只有一种点

假设我有一组数据,我想给我绘制的每个几何体添加一个图例。例如:

x <- rnorm(100, 1)
qplot(x = x, y = 1:100, geom = c("point", "smooth"))
其中我指定了“图例标题”、“点”和“平滑”名称


我该怎么做呢?

添加额外信息的最简单方法是使用注释而不是图例

(我知道这是一个玩具示例,但ggplot在只有一种点和一种线的情况下不包括图例是明智的。您可以创建图例,但默认情况下,它会占用更多的空间和墨水,并且需要更多的工作。当只有一种点时,其含义应该从x轴和y轴上的标签中清楚从图形的一般上下文中。由于缺少其他信息,读者会推断出线条是将某些函数拟合到点的结果。他们唯一不知道的是灰色误差区域的具体函数和含义。可以是简单的标题、注释或绘图外的文本。)

另一个选项是注释层。在这里,我使用了mean和max函数来猜测文本的合理位置,但是可以更好地处理真实数据,也可以使用像
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")

注释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

x谢谢你的解决方案。不过,我确实想要一个图例。这是一个非常基本的要求,我很惊讶像ggplot2这样复杂的软件包不能处理它。谢谢你的尝试。+1因为我可以用这种方式创建一个临时图例。我会等待,看看是否有人知道如何制作一个合适的图例。
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)")
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")
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