Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: One legend with two visual properties derived from common variable

Tags:

r

legend

ggplot2

How can I get a single legend that captures both colour and size?

I was under the impression that a common legend is default if a common variable is used, but the following example shows I am missing something.

library(ggplot2)

input <- as.data.frame(matrix(runif(60),nrow=20,ncol=3))
colnames(input) <- c("A","B","C")

p <- ggplot(input,aes(A,B,size=C,color=C)) + geom_point() 

enter image description here

Thanks to Arun for a comment that prompted this edit. So, if one just uses size (and forgets color) one gets a legend that depicts three sizes but many more sizes are depicted in the plot.

enter image description here

So what I would be after is similar behaviour - a legend that shows some values of the common variable and depicts the corresponding sizes and colors.

like image 540
Rahul Savani Avatar asked Mar 03 '13 18:03

Rahul Savani


1 Answers

The colorbar cannot be merged, but a normal legend can,

p + guides(colour = guide_legend())
like image 95
baptiste Avatar answered Nov 16 '22 03:11

baptiste