Recent version of ggplot2 not fully including scales in legend when using drop=FALSE


I have found that my ggplots are not behaving as they once had. I often make use of the "drop=FALSE" option inside a scale_X_manual command in order to maintain the same legend across multiple plots. However, with R version 4.3.X, this command appears to not work as intended. Please see a reprex below. The label for the unused factor level appears appropriately, but the corresponding point and color do not (a purple dot is missing from the legend in the below example).

When reverting to R version 4.2.X, the desired purple dot appears as expected. I have confirmed this finding with others in my organization. Are others experiencing the same?


# Dataset contains three species: setosa, versicolor, and virginica

# Suppose we have a factor with one level not represented in the data: unguicularis
iris$Species = factor(iris$Species, levels = c("setosa", "versicolor", "virginica", "unguicularis"))

# We can include unguicularis in a ggplot legends through the drop=false command
myplot = ggplot(data = iris, mapping = aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point() +
  scale_color_manual(values = c("setosa" = "black", "versicolor" = "red", "virginica" = "blue", "unguicularis" = "purple"), drop = FALSE)

# However, the legend will only include the factor labels, not a corresponding shape or color

Created on 2024-03-24 with reprex v2.1.0

I can confirm the behavior, and it is not tied to the choice of "purple"; the same happens if I change "purple" to "green".

Update: teunbrand has commented on this issue here (github).

This is the relevent comment: "By default, guide_legend() now only draws a key glyph for a layer when the value is in the layer's data. To revert to the old behaviour, you can still set show.legend = c({aesthetic} = TRUE)"

1 Like