简体   繁体   English

使用点图将图例添加到ggplot2线

[英]Add legend to ggplot2 line with point plot

I have a question about legends in ggplot2. 我对ggplot2中的图例有疑问。 I managed to plot two lines and two points in the same graph and want to add a legend with the two colors used. 我设法在同一张图中绘制两条线和两个点,并希望使用两种颜色添加图例。 This is the code used 这是使用的代码

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

and the output is enter image description here 输出是在此处输入图像描述

I try to use scale_color_manual and scale_shape_manual and scale_line_manual,but they don't work . 我尝试使用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')) +

I want it like this 我想要这样

Here is the simple data if it can help you. 如果可以帮助您,这是简单的数据。

5   0.49216 0.45148  
10  0.3913  0.35751  
15  0.32835 0.30361

data_p DATA_P

I would approach this problem in two steps. 我将分两个步骤解决这个问题。

Generally, to get stuff in the guides, ggplot2 wants you to put "aesthetics" like colour inside the aes() function. 通常,为了获得指南中的内容,ggplot2希望您将像颜色之类的“美学”放入aes()函数中。 I typically do this inside the ggplot() rather than individually for each "geom", especially if everything kind of makes sense in a single dataframe. 我通常在ggplot()中执行此操作,而不是针对每个“ geom”单独执行此操作,尤其是如果在单个数据帧中一切都有意义的话。

My first step would be to remake your dataframe slightly. 我的第一步是稍微重新制作数据框。 I would use the package tidyr (part of the tidyverse, like ggplot2, which is really nice for reformatting data and worth learning as you go), and do something like this 我将使用软件包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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM