Reputation: 3191
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)))
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)
Upvotes: 3
Views: 10039
Reputation: 7790
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))
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))
Upvotes: 11