1

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

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

它看起来像这样:

在此处输入图像描述

现在,我想添加一个图例,这样它会说:

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

我在其中指定“图例标题”、“点”和“平滑”名称。

我该怎么做呢?

4

2 回答 2

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

带有标题的示例 ggplot

另一种选择是注释层。在这里,我使用 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

于 2012-12-03T18:55:31.607 回答
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

在此处输入图像描述

于 2012-12-03T21:56:47.227 回答