我是 ggplot 的相对新手,并使用此处包含的数据和代码制作了下图\xe2\x80\xa6
\n\n数据在这里
\n\nData <- structure(list(IndID = structure(1:17, .Label = c("AA", "BB", \n"CC", "DD", "EE", "FF", "GG", "HH", "II", "JJ", "KK", "LL", "MM", \n"NN", "OO", "PP", "QQ"), class = "factor"), Avg = c(7.95, 10.483, \n5.951, 7.359, 10.465, 10.745, 14.402, 81.417, 67.087, 4.254, \n34.393, 47.324, 60.713, 75.446, 64.527, 28.779, 54.764), AvgSE = c(1.685, \n2.949, 1.097, 2.607, 4.256, 3.539, 1.702, 3.314, 0.714, 0.302, \n1.154, 1.827, 0.573, 1.292, 1.955, 1.341, 1.949), OBS = c(7.667, \n10, 8, 7.5, 14, 10.333, 12, 91, 53, 7, 29, 36.5, 43, 61, 61, \n24, 38)), .Names = c("IndID", "Avg", "AvgSE", "OBS"), class = "data.frame", row.names = c(NA, \n-17L))\nRun Code Online (Sandbox Code Playgroud)\n\n看起来像这样
\n\n> head(Data)\n IndID Avg AvgSE OBS\n1 AA 7.950 1.685 7.667\n2 BB 10.483 2.949 10.000\n3 CC 5.951 1.097 8.000\n4 DD 7.359 2.607 7.500\n5 EE 10.465 4.256 14.000\n6 FF 10.745 3.539 10.333\nRun Code Online (Sandbox Code Playgroud)\n\n我的情节代码在这里
\n\nggplot(Data, aes(x=IndID, y=Avg))+\n geom_point()+\n geom_errorbar(aes(ymin=Avg-AvgSE, ymax=Avg+AvgSE))+\n geom_point(aes(y=OBS),color="red", pch = 8) +\n theme(axis.text.x=element_text(angle=30, hjust=1))\nRun Code Online (Sandbox Code Playgroud)\n\n
我绘制了两组不同的点。我没有在aes()参数中指定一个color或的因素shape。我见过的大多数 SO 帖子都使用这些参数,默认情况下会出现图例。据我所知(在看过很多帖子并使用 R Graphics Cookbook 之后),像在基本 R 函数中那样构建图例并不是那么简单。
是按照此处建议的方式更改数据结构的最佳选择http://stackoverflow.com/questions/17713919/r-ggplot-2-geom-points-how-to-add-a-legend使用Melt() 吗?
\n\n或者还有其他方法可以创造传奇吗?
\n\n在上图中,我只是想要每组点的图例。一个用于黑色(平均)点,另一个用于 OBS 点。
\n\n任何建议,将不胜感激!
\n我认为你最好重新调整你的数据,但这是一种方法。您需要映射颜色来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))
Run Code Online (Sandbox Code Playgroud)

要按照您想要的方式获取颜色,请使用scale_colour_manual(),然后您可以使用 覆盖图例的形状guides():
p + scale_colour_manual(values = c("black", "red")) +
guides(colour = guide_legend(override.aes = list(shape = c(16, 8))))
Run Code Online (Sandbox Code Playgroud)
