categorize with color and size in one ggplot legen

2019-08-08 10:42发布

问题:

I would like to plot some data with are categorized in ggplot by size and color. For example:

require(ggplot2)

ggplot(mtcars, aes(wt, mpg)) + 
  geom_point(aes(size = qsec, color = qsec)) + 
  scale_colour_gradient(limits=c(15, 23), low = "blue", high = "red")

How would I alter this so that both the color and size are represented in the same legend?

回答1:

First of all, you need to specify guide = 'legend' within scale_color_gradient (the default is "colourbar"). And then of course you need to use the same limits for the color and the size scales.

ggplot(mtcars, aes(wt, mpg)) + 
  geom_point(aes(size = qsec, color = qsec)) + 
  scale_colour_gradient(limits=c(15, 23), low = "blue", high = "red", guide = 'legend') +
  scale_size_continuous(limits=c(15, 23))


标签: r ggplot2