scale_color_manual with drop=FALSE: how to keep icon?

I'd like to make a ggplot that includes unused levels in the legend:

df <- data.frame(x = 1:3,
                 y = 1:3,
                 z = factor(letters[1:3], levels = letters[1:4]))

ggplot(data = df) +
  geom_point(aes(x=x, y=y, color = z)) +
  scale_color_manual(drop = FALSE,
                     values = c(a = "red",
                                b = "blue",
                                c = "yellow",
                                d = "green"))

This produces:
image

However, I'd like to see a "green" dot next to "d" in the legend. Is there a way to do that without basically making the whole thing manually with override.aes?

to make sure drop = FALSE works, also add show.legend = TRUE to the layer, like so:

ggplot(data = df) +
  geom_point(aes(x=x, y=y, color = z), show.legend = TRUE) +
  scale_color_manual(drop = FALSE,
                     values = c(a = "red",
                                b = "blue",
                                c = "yellow",
                                d = "green"))
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.