【问题标题】:Select ggplot legend items and preserve palette colors [duplicate]选择ggplot图例项目并保留调色板颜色[重复]
【发布时间】:2026-01-19 01:50:02
【问题描述】:

这里回答了类似的问题,但不是针对我的特定问题。

让我们有一个数据框和 ggplot 条:

d <- data.frame(
  letters = LETTERS[1:10],
  numbers = 11:20
)

ggplot(d, aes(x = letters, y = numbers, fill = letters)) +
  geom_bar(stat = "identity")

我只需要在图例中显示 A 和 J 项目。我可以使用这段代码,但是渐变调色板完全损坏了,我不知道如何把它放回去。

ggplot(d, aes(x = letters, y = numbers, fill = letters)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(breaks = c("A", "J"), values = d$letters)

你知道吗?

类似问题:

【问题讨论】:

标签: r ggplot2 legend


【解决方案1】:

您必须指定scale_fill_discrete,因此您的代码应如下所示:

ggplot(d, aes(x = letters, y = numbers, fill = letters)) +
  geom_bar(stat = "identity") +
  scale_fill_discrete(breaks = c("A", "J"))

【讨论】: