1

I have 4 labels for my area plot's legend, but I only want to show 2 of those labels:

library(ggplot2)

tibble(
  x = rep(1:16, each = 4),
  y = rnorm(64, mean = 3),
  labels = factor(rep(1:4, 16))
) %>%
  ggplot(aes(x = x, y = y, fill = labels)) +
  scale_fill_discrete(labels = c("A", "B", "C", "D")) +
  geom_area()

enter image description here

I'd like to completely remove labels A and C, so that only B and D is visible in the legend. Only the legend changes, the plot should remain the same. I can't find how to do this. I tried setting the labels to an NULL or NA. When I make the A and C legend labels an empty string, the A and C disappear, but the color square is still visible. I don't even want the color square:

scale_fill_discrete(labels = c("", "B", "", "D")) +

enter image description here

zx8754
  • 52,746
  • 12
  • 114
  • 209
at.
  • 50,922
  • 104
  • 292
  • 461

1 Answers1

3

Your labels are actually numbers so you could specify them with the breaks argument like 2 and 4 and keep them with the labels B and D like this:

library(tidyverse)

tibble(
  x = rep(1:16, each = 4),
  y = rnorm(64, mean = 3),
  labels = factor(rep(1:4, 16))
) %>%
  ggplot(aes(x = x, y = y, fill = labels)) +
  scale_fill_discrete(breaks = c("2", "4"),
                      labels = c("B", "D")) +
  geom_area()

Created on 2023-04-06 with reprex v2.0.2

Quinten
  • 35,235
  • 5
  • 20
  • 53