R语言 选择性删除图例标签[重复]

pkmbmrz7  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(146)

此问题已在此处有答案

Only displaying some legend contents [duplicate](1个答案)
11天前关闭
我的面积图图例有4个标签,但我只想显示其中2个标签:

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()

我想完全删除标签A和C,以便图例中仅显示B和D。只有图例更改,图应保持不变。我找不到如何做到这一点。我尝试将标签设置为NULLNA。当我将A和C图例标签设置为空字符串时,A和C消失,但彩色方块仍然可见。我甚至不想要彩色方块:

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

cu6pst1q

cu6pst1q1#

你的标签实际上是数字,所以你可以用breaks参数来指定它们,比如2和4,并像这样用labels B和D来保存它们:

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()

创建于2023-04-06带有reprex v2.0.2

相关问题