user2568648
user2568648

Reputation: 3191

ggplot2 geom_point legend when size is mapped to a variable

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)

Upvotes: 3

Views: 10039

Answers (1)

Peter
Peter

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

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

Upvotes: 11

Related Questions