r - 删除ggplot中图例键周围的填充

标签 r ggplot2

我想删除图例周围的灰色矩形。我尝试了各种方法,但是都没有用。

ggtheme <- 
theme(
axis.text.x = element_text(colour='black'),
axis.text.y = element_text(colour='black'),
panel.background = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
panel.border = element_rect(colour='black', fill=NA),
strip.background = element_blank(),
legend.justification = c(0, 1),
legend.position = c(0, 1),
legend.background = element_rect(colour = NA),
legend.key = element_rect(colour = "white", fill = NA),
legend.title = element_blank()
)

colors <- c("red", "blue")
df <- data.frame(year = c(1:10), value = c(10:19), gender = rep(c("male","female"),each=5))
ggplot(df, aes(x = year, y = value)) + geom_point(aes(colour=gender))  +
stat_smooth(method = "loess", formula = y ~ x, level=0, size = 1, 
    aes(group = gender, colour=gender)) +
ggtheme + scale_color_manual(values = colors) 

enter image description here

最佳答案

您会在图例键中得到这种灰色,因为您使用的stat_smooth()默认情况下也会使行周围的置信区间充满一些填充(如果fill=内部未使用aes(),则为灰色)。

一种解决方案是,如果不需要置信区间,则将se=FALSE设置为stat_smooth()

  +stat_smooth(method = "loess", formula = y ~ x, level=0, size = 1, 
              aes(group = gender, colour=gender),se=FALSE) 

另一种解决方案是使用函数guides()override.aes=从图例中删除填充,但保持行周围的置信区间。
  + guides(color=guide_legend(override.aes=list(fill=NA)))

关于r - 删除ggplot中图例键周围的填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21066077/

相关文章:

r - 使用 ggplot 在背景图像上绘制数据

r - 如何在 ggplot2 中绘制置信区间限制的虚线?工作室R

R - countifs 像 excel

r - 使用 GGPLOT 创建 ROC 曲线

旋转整个 ggplot() 而不旋转任何文本 R

r - 在 ggplot 中自定义图例

r - 你如何编写你的包文档?

r - Rstudio 更有意义的窗口标题

R:根据条件的行值填充data.frame中的新列?

r - 如何计算R中的最小生成树