commscho
commscho

Reputation: 380

ggplot2: What controls the size of the point in the legend when size is a mapped aesthetic?

When you have both a linetype and shape aesthetic (with geom_path and geom_point, respectively), it can sometimes be difficult to make out the points in the legend because they overlap with the line.

Here's a working example. I have a weighted linear model and want to plot predicted data along with the observed data.

iris$wts <- runif(nrow(iris), min = 0.2, max = 3) 
fitw <- lm(Petal.Length ~ Petal.Width * Species, data = iris, 
           weights = wts)

newdat <- data.frame(
  Petal.Width = rep(seq(from = min(iris$Petal.Width),
                        to = max(iris$Petal.Width), length.out = 100),
                    3),
  Species = c(rep("setosa", 100), rep("versicolor", 100), rep("virginica", 100))
)
newdat$Petal.Length <- predict(fitw, newdata = newdat)

library(ggplot2)
ggplot(data = newdat, aes(y = Petal.Length, x = Petal.Width,
                              colour = Species)) +
  geom_path(aes(linetype = Species), size = 1.1) +
  geom_point(data = iris, aes(x = Petal.Width, y = Petal.Length, shape = Species,
                              size = wts), show.legend = TRUE) +
  scale_shape_discrete(name = "Species") +
  scale_size_identity(guide = "none") 

Gives:

plot

It's a little hard to tell how the symbols map to the factor levels. I could make the line less thick, but of course I might not want to do that. If I weren't mapping size to wts, I could just use the size argument in geom_point. But since size is mapped to wts, the legend's representation of the point shape seems to fall back to the default, regardless of whether the line size has been changed.

Is there any way to change the size of the point in the legend for the shape/color aesthetics?

Upvotes: 3

Views: 173

Answers (1)

Algebreaker
Algebreaker

Reputation: 118

I used this post for guidance - apparently it's only possible to scale the points and lines separately using the underlying grid system:

library(ggplot2)
ggplot(data = newdat, aes(y = Petal.Length, x = Petal.Width,
                          colour = Species)) +
  geom_path(aes(linetype = Species), size = 1.1) +
  geom_point(data = iris, aes(x = Petal.Width, y = Petal.Length, shape = Species,
                              size = wts), show.legend = TRUE) + 
  scale_shape_discrete(name = "Species") +
  scale_size_identity(guide = "none")


library(grid)

grid.ls(grid.force())    # To get the names of all the grobs in the ggplot

# The edit - to set the size of the point in the legend to 4 mm
grid.gedit("key-3-1-2.4-2-4-2", size = unit(5, "mm"))
grid.gedit("key-4-1-2.5-2-5-2", size = unit(5, "mm"))
grid.gedit("key-5-1-2.6-2-6-2", size = unit(5, "mm"))

Output: enter image description here

Upvotes: 0

Related Questions