gpt4 book ai didi

r - 使用平滑时无法删除图例符号后面的灰色区域

转载 作者:行者123 更新时间:2023-12-04 11:32:20 25 4
gpt4 key购买 nike

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

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

我在下面有一个 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

enter image description here

最佳答案

这是一个非常棘手的解决方法,基于这样一种概念,即如果您将事物映射到 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

enter image description here

关于r - 使用平滑时无法删除图例符号后面的灰色区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33779219/

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