[英]Add legend to ggplot2 line with point plot
我对ggplot2中的图例有疑问。 我设法在同一张图中绘制两条线和两个点,并希望使用两种颜色添加图例。 这是使用的代码
P <- ggplot() + geom_point(data = data_p,aes(x = V1,y = V2),shape = 0,col = "#56B4E9") + geom_line(data = data_p,aes(x = V1,y = V2),col = "#56B4E9")+geom_point(data = data_p,aes(x = V1,y = V3),shape = 1,col = "#009E73") + geom_line(data = data_p,aes(x = V1,y = V3),col = "#009E73")
输出是在此处输入图像描述
我尝试使用scale_color_manual和scale_shape_manual和scale_line_manual,但是它们不起作用。
P + scale_color_manual(name = "group",values = c('#56B4E9' = '#56B4E9','#009E73' = '#009E73'),
breaks = c('#56B4E9','#009E73'),labels = c('B','H')) +
如果可以帮助您,这是简单的数据。
5 0.49216 0.45148
10 0.3913 0.35751
15 0.32835 0.30361
我将分两个步骤解决这个问题。
通常,为了获得指南中的内容,ggplot2希望您将像颜色之类的“美学”放入aes()函数中。 我通常在ggplot()中执行此操作,而不是针对每个“ geom”单独执行此操作,尤其是如果在单个数据帧中一切都有意义的话。
我的第一步是稍微重新制作数据框。 我将使用软件包tidyr(tidyverse的一部分,例如ggplot2,它非常适合重新格式化数据并值得您随时学习),并执行类似的操作
#key is the new variable that will be your color variable
#value is the numbers that had been in V2 and V3 that will now be your y-values
data_p %>% tidyr::gather (key = "color", value = "yval", V2, V3)
#now, I would rewrite your plot slightly
P<-(newdf %>% ggplot(aes(x=V1,y=yval, colour=color))
#when you put the ggplot inside parentheses,
#you can add each new layer on its own line, starting with the "+"
+ geom_point()
+ geom_line()
+ scale_color_manual(values=c("#56B4E9","#009E73"))
#theme classic is my preferred look in ggplot, usually
+ theme_classic()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.