为什么我不能将 ggplot 图例框的背景颜色更改为白色?(其他颜色也可以)

adk*_*ane 5 r ggplot2

我试图通过添加 来重新着色我的 ggplot 对象的图例theme(legend.key = element_rect(fill = "white")),但图例仍然是灰色的。奇怪的是,当我选择 以外的颜色时,此代码有效"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'
Run Code Online (Sandbox Code Playgroud)

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

由reprex 包(v0.3.0)于 2021-01-26 创建

我尝试了一些东西guide_legend(),但似乎无法破解它。

如何将图例框变成白色?


ste*_*fan 7

除了设置 的 之外,filllegend.key还必须设置的fill颜色或通过 例如。原因是图例键中的填充颜色反映了由 绘制的标准错误带的填充颜色:key_glyphswhiteNAguide_legendgreygeom_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'
Run Code Online (Sandbox Code Playgroud)