ana.la
ana.la

Reputation: 119

How do I add a reference line with separate legend in geom_line?

I have a small dataset that I need to plot with a reference line.

ex <- tibble(name = rep(c("A","B","C"),each = 3),
             group = rep(c("group1","group2","group3"), 3),
             value = c(1,2,3,1.5,2.5,3,0.5,1.8,4))
ex %>% 
  ggplot(aes(x = group, y = value, color = name, group = name)) +
  geom_line()`

This gives me:
plot 1

Now I want to add a reference line. I can add points like this:

ex %>% 
  ggplot(aes(x = group, y = value, color = name, group = name)) +
  geom_line() +
  geom_point(aes(x = "group1", y = 3, fill = "ref")) +
  geom_point(aes(x = "group2", y = 3, fill = "ref")) +
  geom_point(aes(x = "group3", y = 3, fill = "ref"))

Which gives me:
plot 2

Now how do I connect the dots and still have this line as a separate legend? If I add more rows to my original tibble with the reference values, I can add the line but it shows in my original legend and I need it in a separate one, like the dots.


ex <- ex %>% 
  add_row(name = "ref",
          group = "group1",
          value= 3) %>% 
  add_row(name = "ref",
          group = "group2",
          value= 3) %>% 
  add_row(name = "ref",
          group = "group3",
          value= 3)

ex %>% 
  ggplot(aes(x = group, y = value, color = name, group = name)) +
  geom_line() +
  geom_point(aes(x = "group1", y = 3, fill = "ref")) +
  geom_point(aes(x = "group2", y = 3, fill = "ref")) +
  geom_point(aes(x = "group3", y = 3, fill = "ref"))

Which gives me this:
plot 3

What am I missing?

Upvotes: 1

Views: 773

Answers (1)

Duck
Duck

Reputation: 39613

Maybe you are looking for this. You can enable the linetype option in aes to create a legend for the new line you want:

library(ggplot2)
#Data
ex <- tibble(name = rep(c("A","B","C"),each = 3),
             group = rep(c("group1","group2","group3"), 3),
             value = c(1,2,3,1.5,2.5,3,0.5,1.8,4))
#Create data for ref
ref <- data.frame(group=c("group1","group2","group3"),value=3,name=NA)
#Plot 
ggplot(ex,aes(x = group, y = value, color = name, group = name)) +
  geom_line()+
  geom_line(data=ref,aes(x=group,y=value,group=1,linetype='ref'))+
  geom_point(data=ref,aes(x=group,y=value,group=1),show.legend = F)+
  scale_linetype_manual("ref", values=c(1,1,1,1))

Output:

enter image description here

And if you want shapes in all of your legends and lines try this:

#Plot 2
ggplot(ex,aes(x = group, y = value, color = name, group = name)) +
  geom_line()+
  geom_point()+
  geom_line(data=ref,aes(x=group,y=value,group=1,linetype='ref'))+
  geom_point(data=ref,aes(x=group,y=value,group=1),show.legend = T)+
  scale_linetype_manual("ref", values=c(1,1,1,1))

Output:

enter image description here

Upvotes: 2

Related Questions