Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 geom_point legend when size is mapped to a variable

Tags:

legend

ggplot2

I am creating a plot in which the size of points is proportional to the values of a given variable, which I then square to increase the difference in sizes between points...

# Using example from https://www3.nd.edu/~steve/computing_with_data/11_geom_examples/ggplot_examples.html #

library(ggplot2)
str(mtcars)

p <- ggplot(data = mtcars, aes(x = wt, mpg))
p + geom_point(aes(size = (qsec^2)))

enter image description here

From the resulting plot, is there a way to specify the size of the points which are shown in the legend and change the legend labels in order to reflect the original values and not the square of these values? (As edited by hand on the plot)

like image 718
user2568648 Avatar asked Oct 24 '25 19:10

user2568648


1 Answers

Use scale_size to modify the legend. By setting the breaks and labels you can generate the graphic you want. Here are two examples.

Example 1: Build the scale to show a five number summary of mtcars$qsec and show the labels in the original units.

library(ggplot2)

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point(mapping = aes(size = qsec^2)) +
  scale_size(name   = "qsec",
             breaks = fivenum(mtcars$qsec)^2,
             labels = fivenum(mtcars$qsec))

enter image description here

Example 2: show the legend with qsec^2. The expression wrapper will let you format the labels too look good.

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point(mapping = aes(size = qsec^2)) +
  scale_size(name   = expression(qsec^2),
             breaks = c(15, 17, 19, 21)^2,
             labels = expression(15^2, 17^2, 19^2, 21^2))

enter image description here

like image 157
Peter Avatar answered Oct 27 '25 01:10

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!