ggplot2 additional legend

Published by onesixx on

 

 

library(ggplot2)

mtcar <- data.frame(mtcars, cl=factor(mtcars$cyl))

p <- ggplot(mtcar, aes(mpg, wt)) + geom_point()
p <- p+ geom_point(data=mtcar[mtcar$cl==8,], mapping=aes_string(x="mpg", y="wt"), color='red', shape=0, size=3)+
        geom_point(aes(fill="")) + 
        guides(fill=guide_legend("Class A", override.aes=list(size=3, shape=0, color= "red"), order=1))
p <- p+ geom_point(data=mtcar[mtcar$cl==4,], mapping=aes_string(x="mpg", y="wt"), color='blue',shape=2, size=3)+
        geom_point(aes(size="")) + 
        guides(size=guide_legend("Class B", override.aes=list(size=3, shape=2, color="blue"), order=2))
p

dummy <- ""
p <- ggplot(mtcar, aes(mpg, wt)) + geom_point()
p <- p+ geom_point(data=mtcar[mtcar$cl==8,], mapping=aes_string(x="mpg", y="wt", fill="dummy"), color='blue', shape=0, size=3)+
        guides(fill= guide_legend("Class A", order=1))
p <- p+ geom_point(data=mtcar[mtcar$cl==4,], mapping=aes_string(x="mpg", y="wt", color="dummy"),              shape=2, size=3)+
        guides(color=guide_legend("Class B", override.aes=list(color='red'),order=2))
p

 

https://learnr.wordpress.com/2010/03/23/ggplot2-changing-the-default-order-of-legend-labels-and-stacking-of-data/

 

Categories: ggplot2

onesixx

Blog Owner

Leave a Reply

Your email address will not be published.