Home > OS >  ggplot: change values shown in legend for point size aesthetic
ggplot: change values shown in legend for point size aesthetic

Time:02-26

When I use the size aesthetic with geom_point() in ggplot, I often want to broaden the range of values shown in the default legend. In this plot, for example, there are a couple of points with a value of hp much smaller than the smallest value shown in the legend (100), and the reader may have trouble guessing what that value might be:

library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg, size = hp))   
  geom_point()

Created on 2022-02-25 by the enter image description here

If you want to emphasise differences within the range (whilst losing the area-proportionality that makes such plots more 'honest'), you can use a transformation too:

sq <- scales::trans_new("squared", function(x) x^2, sqrt)

ggplot(mtcars, aes(x = wt, y = mpg, size = hp))   
  geom_point(shape = 21, fill = "deepskyblue3")  
  scale_size_continuous(range  = c(0.1, 10), 
                        limits = c(0, 350), 
                        breaks = c(0, 50, 100, 150, 200, 250, 300, 350),
                        trans  = sq)  
  theme_bw()

enter image description here

  • Related