r - 未指定 aes() 颜色和形状时 ggplot 中的图例

标签 r ggplot2

我是 ggplot 的相对新手,并使用此处包含的数据和代码制作了下图......

数据在这里

Data <- structure(list(IndID = structure(1:17, .Label = c("AA", "BB", 
"CC", "DD", "EE", "FF", "GG", "HH", "II", "JJ", "KK", "LL", "MM", 
"NN", "OO", "PP", "QQ"), class = "factor"), Avg = c(7.95, 10.483, 
5.951, 7.359, 10.465, 10.745, 14.402, 81.417, 67.087, 4.254, 
34.393, 47.324, 60.713, 75.446, 64.527, 28.779, 54.764), AvgSE = c(1.685, 
2.949, 1.097, 2.607, 4.256, 3.539, 1.702, 3.314, 0.714, 0.302, 
1.154, 1.827, 0.573, 1.292, 1.955, 1.341, 1.949), OBS = c(7.667, 
10, 8, 7.5, 14, 10.333, 12, 91, 53, 7, 29, 36.5, 43, 61, 61, 
24, 38)), .Names = c("IndID", "Avg", "AvgSE", "OBS"), class = "data.frame", row.names = c(NA, 
-17L))

看起来像这样
> head(Data)
  IndID    Avg AvgSE    OBS
1    AA  7.950 1.685  7.667
2    BB 10.483 2.949 10.000
3    CC  5.951 1.097  8.000
4    DD  7.359 2.607  7.500
5    EE 10.465 4.256 14.000
6    FF 10.745 3.539 10.333

我的情节代码在这里
ggplot(Data, aes(x=IndID, y=Avg))+
    geom_point()+
    geom_errorbar(aes(ymin=Avg-AvgSE, ymax=Avg+AvgSE))+
    geom_point(aes(y=OBS),color="red", pch = 8) +
    theme(axis.text.x=element_text(angle=30, hjust=1))

enter image description here

我绘制了两组不同的点。我没有在 aes() 中指定的因素作为 color 的参数或 shape .我见过的大多数 SO 帖子都使用这些参数,之后默认出现一个图例。据我所知(在看到许多帖子并使用 R Graphics Cookbook 之后),像在基本 R 函数中那样构建图例并不那么直接。

是这里建议的更改数据结构的最佳选择 http://stackoverflow.com/questions/17713919/r-ggplot-2-geom-points-how-to-add-a-legend使用融化()?

还是有其他方法可以创造传奇?

在我上面的图中,我只想要每组点的图例。一个用于黑色(平均)点,另一个用于 OBS 点。

任何建议,将不胜感激!

最佳答案

我认为你真的最好 reshape 你的数据,但这是一种方法。您需要在 aes() 中映射颜色创造一个传奇。您可以将其映射到文本字符串:

p <- ggplot(Data, aes(x=IndID, y=Avg))+
  geom_point(aes(color = "Avg"))+
  geom_errorbar(aes(ymin=Avg-AvgSE, ymax=Avg+AvgSE))+
  geom_point(aes(y=OBS, color = "OBS"), pch = 8, show_guide = T) +
  theme(axis.text.x=element_text(angle=30, hjust=1))

enter image description here

要获得所需的颜色,请使用 scale_colour_manual() ,然后您可以使用 guides() 覆盖图例的形状:
p + scale_colour_manual(values = c("black", "red")) + 
  guides(colour = guide_legend(override.aes = list(shape = c(16, 8))))

enter image description here

关于r - 未指定 aes() 颜色和形状时 ggplot 中的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19945629/

相关文章:

r - R 包的 tests/和 inst/tests/之间的区别

r - 从列表中选择多个元素

r - "Density"曲线叠加在直方图上,其中纵轴是频率(又名计数)还是相对频率?

r - 在条形图中保留未使用的级别

r - 使用仅在一列中使用 ':' 和 'x' 作为分隔符/标识符的数据帧

r - 集群中最具代表性的实例

r - %*% 在 R 中是什么意思

r - 使用 ggplot2 在给定的 x 值处绘制数据帧的每行一行

r - 如何使用 ggplot2 在条形图上叠加一条线?

r - geom_raster() 没有填充和图例