gpt4 book ai didi

r - 为什么我不能将 ggplot 图例框的背景颜色更改为白色? (其他颜色效果很好)

转载 作者:行者123 更新时间:2023-12-03 23:00:47 27 4
gpt4 key购买 nike

我试图通过添加 theme(legend.key = element_rect(fill = "white")) 来重新着色我的 ggplot 对象的图例,但图例仍然是灰色的。奇怪的是,当我选择的颜色不是 "white" 时,此代码有效。 .
这是一个带有一些虚拟数据的小例子:

## Dummy data
response <- rnorm(60, 50, 4)
year <- rep(c(1:10), 6)
treatment <- c(rep("A",30), rep("B", 30))
group <- c(rep(1, 20), rep(2, 20), rep(3, 20))
mydata <- data.frame(response, year, treatment, group)


library(ggplot2)

plot <- ggplot(mydata, aes(
x = year,
y = response,
linetype = treatment,
color = as.factor(group)
)) + geom_smooth()

## Specifying 'white' fill
plot + theme(legend.key = element_rect(fill = "white"))
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

## Specifying 'blue' fill
plot + theme(legend.key = element_rect(fill = "blue"))
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

创建于 2021-01-26 由 reprex package (v0.3.0)
我用 guide_legend() 尝试了一些东西但我似乎无法破解它。
如何将图例框变成白色?

最佳答案

除了设置filllegend.key你必须设置 fill key_glyphs的颜色至 whiteNA通过例如guide_legend .原因是grey图例键中的填充颜色反射(reflect)了 geom_smooth 绘制的标准错误色带的填充颜色。 :

response <- rnorm(60, 50, 4)
year <- rep(c(1:10), 6)
treatment <- c(rep("A",30), rep("B", 30))
group <- c(rep(1, 20), rep(2, 20), rep(3, 20))
mydata <- data.frame(response, year, treatment, group)

library(ggplot2)
ggplot(mydata, aes(
x = year,
y = response,
linetype = treatment,
color = as.factor(group)
)) +
geom_smooth() +
guides(color = guide_legend(override.aes = list(fill = NA)),
linetype = guide_legend(override.aes = list(fill = NA))) +
theme(legend.key = element_rect(fill = "white"))
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

关于r - 为什么我不能将 ggplot 图例框的背景颜色更改为白色? (其他颜色效果很好),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65901541/

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