ggplot2: One legend with two visual properties der

2019-04-22 05:17发布

问题:

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() 

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.

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.

回答1:

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

p + guides(colour = guide_legend())


回答2:

I needed to make the labels for size and color the same, and make sure it's working with the same information combined with the guides line.

p+geom_jitter(data=df, aes(x=x, y=y, color=value, size = value)) 
+scale_size_continuous(name = "Legend Name", breaks= c(.25, .50,.75), labels=c(".25",".50",".75"))+scale_colour_gradient(name = "Legend Name", breaks= c(.25, .50,.75), labels=c(".25", ".50",".75"))+ 
guides(colour = guide_legend())


标签: r ggplot2 legend