-2

I have this plot

dat = data.frame(group = rep("A",3),subgroup= c("B","C","D"), value= c(4,5,6),avg = c(4.5,4.5,4.5))
ggplot(dat, aes(x= group, y =value, color = fct_rev(subgroup) ))+ 
  geom_point()+
  geom_point(data = dat  ,aes(x = group, y = avg), color = "blue",pch = 17, inherit.aes = FALSE)

I need to show 2 legends: 1 for the fct_rev(subgroup) which I already there but there is no legend for "avg".

How can i add a legend that is a blue triangle pch 17 with the title "avg?

thank you

user3022875
  • 8,598
  • 26
  • 103
  • 167
  • Possible duplicate of [Two geom\_points add a legend](https://stackoverflow.com/questions/17713919/two-geom-points-add-a-legend) – r.bot Mar 23 '18 at 11:03

2 Answers2

1

Maybe like this?

ggplot(dat, aes(x= group, y =value, color = fct_rev(subgroup) ))+ 
    geom_point()+
    geom_point(data = dat  ,aes(x = group, y = avg,shape = "Mean"), 
                                color = "blue", inherit.aes = FALSE) + 
    scale_shape_manual(values = c('Mean' = 17))
joran
  • 169,992
  • 32
  • 429
  • 468
0

Using data from original post.

Legends do not work like that in ggplot. Why not add a geom_text at the average? I see that you have a column with the average being repeated. This seems like a bad way to handle the data, but irrelevant right now.

My proposed solution:

ggplot(dat)+ 
    geom_point(aes(x= group, y =value, color = subgroup))+
    geom_point(aes(x = group, y = avg), color = "blue",pch = 17, inherit.aes = FALSE) + 
geom_text(aes(x=1, y = 4.5), label = "avg", nudge_x = .1)

You could also add a hline to symbolize the average, which would aesthetically look nicer.

leeum
  • 264
  • 1
  • 13