mzuba
mzuba

Reputation: 1276

Remove some legend entries in ggplot

I would like to remove some legend entries in my ggplot.

Previously, this was possible by defining the breaks parameter in the relevant scale, as explained here. However, that functionality seems to be broken with a recent update.

Example:

ggplot(mtcars) + 
  
  geom_col(aes(x = 1:nrow(mtcars), y = disp, fill = paste(cyl))) +
  
  scale_fill_manual(values = c("grey50", "grey60", "grey70"),
                    breaks = c("4"))

Incorrect plot

While this code snippet only diplays one legend item, as intended, it does not allow to control the colours of the non-displayed elements.

With the breaks attribute omitted:

Correct plot, but wrong legend

Upvotes: 1

Views: 1127

Answers (1)

Stéphane Laurent
Stéphane Laurent

Reputation: 84709

Use a named values argument:

ggplot(mtcars) + 
  geom_col(aes(x = 1:nrow(mtcars), y = disp, fill = paste(cyl))) +
  scale_fill_manual(values = c("4" = "red", "6" = "green", "8" = "blue"),
                    breaks = c("4"))

enter image description here

Upvotes: 4

Related Questions