Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add an extra legend to facet in ggplot

I want to add few individual data points to selected facet and have a legend for them.

library(ggplot2)

ggplot(data=mpg, aes(displ, hwy)) +
  geom_bin2d()+
  facet_wrap(~class) + 
  geom_point(data = data.frame(displ = c(5,3,6,4), hwy = c(25,30,35,27), type="XX", class = "pickup"), colour="blue")

With this I get the legend for counts but how can I add a custom legend for the added points with XX as legend?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to have a legend you have to map on aesthetics, i.e. move color= inside aes() and set your desired color via scale_color_manual:

library(ggplot2)

ggplot(data = mpg, aes(displ, hwy)) +
  geom_bin2d() +
  facet_wrap(~class) +
  geom_point(data = data.frame(
    displ = c(5, 3, 6, 4), 
    hwy = c(25, 30, 35, 27), 
    type = "XX", class = "pickup"), 
    aes(colour = type)) +
  scale_color_manual(values = "blue")

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading