gpt4 book ai didi

r - ggplot2 scale_color_manual 显示图例中的所有值

转载 作者:行者123 更新时间:2023-12-05 03:40:31 28 4
gpt4 key购买 nike

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

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

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,或任何其他逐字返回输入的函数。

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 创建于 2021-06-22 (v1.0.0)

关于r - ggplot2 scale_color_manual 显示图例中的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68088145/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com