ggplot2 scale_color_manual 显示图例中的所有值

ggplot2 scale_color_manual showing all values in legend

我创建并更新了一份报告,其中包含许多不同参数的不同站点。并非每个站点都测量所有参数。我创建了一个手动色标,以便网站在各个地块上显示为相同的颜色。

问题在于,现在手动色标中的每个值都显示在图例中,无论它是否出现在图中。我在下面创建了一个可重现的示例

library(ggplot2)
library(dplyr)

set.seed(123)

df <- tibble(
  site = rep(c("front", "back", "top"), 4),
  x = rnorm(12, 0, 1),
  y = rnorm(12, 0, 2)
) %>% 
  mutate(site = as.factor(site))

my_colors <- c("red", "blue", "green")

names(my_colors) <- levels(df$site)

col_scale <- scale_colour_manual(name = "site", values = my_colors)

ggplot(df, aes(x = x, y = y, color = site)) + 
  theme_bw() + 
  geom_point() + 
  col_scale

df %>% filter(site != "top") %>% 
  ggplot(aes(x = x, y = y, color = site)) + 
  theme_bw() + 
  geom_point() + 
  col_scale

创建以下图:

plot with three sites

plot with two sites

我只希望图中出现的站点显示在图例中。任何帮助将非常感激!谢谢!

这是 ggplot2 中最近的一个错误,请参阅 this issue。临时解决方法可能是指定 limits = force,或 returns 逐字输入的任何其他函数。

library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

set.seed(123)

df <- tibble(
  site = rep(c("front", "back", "top"), 4),
  x = rnorm(12, 0, 1),
  y = rnorm(12, 0, 2)
) %>% 
  mutate(site = as.factor(site))

my_colors <- c("red", "blue", "green")

names(my_colors) <- levels(df$site)

col_scale <- scale_colour_manual(name = "site", values = my_colors,
                                 limits = force)

ggplot(df, aes(x = x, y = y, color = site)) + 
  theme_bw() + 
  geom_point() + 
  col_scale

df %>% filter(site != "top") %>% 
  ggplot(aes(x = x, y = y, color = site)) + 
  theme_bw() + 
  geom_point() + 
  col_scale

reprex package (v1.0.0)

创建于 2021-06-22