【问题标题】:Cannot remove grey area behind legend symbol when using smooth使用平滑时无法移除图例符号后面的灰色区域
【发布时间】:2015-11-18 11:45:45
【问题描述】:

我正在使用带有 GAM 平滑的 ggplot2 来查看两个变量之间的关系。绘图时,我想删除两种类型变量符号后面的灰色区域。为此,我会使用theme(legend.key = element_blank()),但在使用平滑时似乎不起作用。

谁能告诉我如何去除图例中两条黑线后面的灰色区域?

我在下面有一个 MWE。

library(ggplot2)

len <- 10000
x <- seq(0, len-1)
df <- as.data.frame(x)
df$y <- 1 - df$x*(1/len)
df$y <- df$y + rnorm(len,sd=0.1)
df$type <- 'method 1'
df$type[df$y>0.5] <- 'method 2'

p <- ggplot(df, aes(x=x, y=y)) + stat_smooth(aes(lty=type), col="black", method = "auto", size=1, se=TRUE)
p <- p + theme_classic()
p <- p + theme(legend.title=element_blank())
p <- p + theme(legend.key = element_blank()) # <--- this doesn't work?
p

【问题讨论】:

  • 试试element_rect(fill = NA)
  • 这似乎不起作用。我猜想——当我使用 fill = "green" 时,盒子会变成深绿色,已经涉及到某种背景。将进一步调查。
  • @CathG 是的,海似乎在传说中。不过我找到了解决方法。

标签: r ggplot2 legend


【解决方案1】:

这是一个非常老套的解决方法,基于这样一种概念,即如果您将事物映射到 ggplot 中的美学,它们就会出现在图例中。 geom_smooth 具有填充美学,如果需要,可以为不同的组使用不同的颜色。如果很难解决下游问题,有时将那些不需要的项目完全排除在图例之外会更容易。在您的情况下, se 的颜色出现在图例中。因此,我创建了两个 geom_smooths。一种没有线颜色(但按类型分组)来创建绘制的 se,另一种具有映射到 aes 但 se 设置为 false 的线型。

p <- ggplot(df, aes(x=x, y=y)) + 
  #first smooth; se only
  stat_smooth(aes(group=type),col=NA, method = "auto", size=1, se=TRUE)+
  #second smooth: line only
  stat_smooth(aes(lty=type),col="black", method = "auto", size=1, se=F) +
  theme_classic() +
  theme(
    legend.title = element_blank(),
    legend.key = element_rect(fill = NA, color = NA)) #thank you @alko989

【讨论】:

  • 您可以在最后一个element_rect 中添加colour = NA 以删除框
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多