Felipe Dalla Lana
Felipe Dalla Lana

Reputation: 625

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.

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)

enter image description here

Upvotes: 0

Views: 220

Answers (1)

Djork
Djork

Reputation: 3369

You can try reshaping your data frame to allow you to set color aes to group and linetype aes to the variable type.

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

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

enter image description here

Upvotes: 1

Related Questions