简体   繁体   English

geom_line ggplot2中同一组的两个不同图例

[英]two different legends for the same group in geom_line ggplot2

I want to plot two variables of the same groups, but I need that they are present in two separated legends, one for each variable (solid and dashed line) Because they share the same group, ggplot is showing them in the same legend. 我想绘制同一组中的两个变量,但我需要它们出现在两个单独的图例中,每个变量对应一个图例(实线和虚线)。因为它们共享同一组,所以ggplot将它们显示在同一图例中。

The code below reproduces my problem. 下面的代码重现了我的问题。

df = data.frame(
  group_ = c("A","A","A","A","A","B","B","B","B","B"),
  var1 = c(1:10),
  var2 = c(11:20),
  x_ = c(1:5))


ggplot(data=df , group = a)+
  geom_line(aes(x= x_, y=var1, color= group_))+
  geom_line(aes(x= x_, y=var2, color= group_), lty=2)

在此处输入图片说明

You can try reshaping your data frame to allow you to set color aes to group and linetype aes to the variable type. 您可以尝试重塑数据框的aes ,以允许您将颜色aes设置为分组,并将线型aes设置为变量类型。

library(reshape2)
df2 <- melt(df, id.vars=c("x_", "group_"))

ggplot(data=df2)+
  geom_line(aes(x= x_, y=value, color= group_, lty=variable)) 

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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