使用 ggplotly 删除 geom_smooth 置信区间上的边界线

Remove border lines on geom_smooth confidence interval using ggplotly

我正在构建一个非常密集的情节,但我遇到了 geom_smooth 的基本问题,我似乎无法找到任何答案。这是 geom_smooth(method = "lm") 现在的情节:

当我构建绘图的 geom_smooth() 部分时,我想更改线条颜色。当我这样做时,它会在我的置信区间内绘制新线,

正在调用 geom_smooth(method = "lm", color = "black") returns 这个:

有没有简单的方法去掉边框线,但主线保持黑色?

编辑:我无法提供带有数据的完整代码,但提供了可以在此处重现错误的情况。你只需要这个就可以回答这个问题。根据下面的评论,它可能是与 plotly (ggplotly).

的交互
library(ggplot2)
library(plotly)
df <- data.frame(
    Demographic = rnorm(1:100),
    Proficiency = rnorm(1:100),
    N.Tested = rnorm(1:100)
)

a <- ggplot(data = df, 
        aes(x = Demographic, 
            y = Proficiency)
)
b <- a + geom_point(aes(
    text = "to be replaced",
    color = N.Tested,
    size = N.Tested
),
show.legend = FALSE)
c <- b + scale_color_gradient2(low = "firebrick4", high = "gold", mid = "orange", midpoint=300)
d <- c + geom_smooth(method = "lm", color="black")

ggplotly(d)

ggplotly 经常给出意想不到的结果。如果你想要的最终产品是一个 plotly graph,那么通常最好直接进入 plotly API。使用 plotly API 还可以访问比 ggplotly 更广泛的选项。

然而,不幸的是,plotly 没有 geom_smooth 提供的方便的内置统计计算。因此,我们首先使用 lm()predict.lm()

计算拟合和误差范围
lm1 = lm(Proficiency~Demographic, data=df)
lm.df = data.frame(Demographic = sort(df$Demographic), 
                   Proficiency = predict(lm1)[order(df$Demographic)],
                   se = predict(lm1, se.fit = T)$se.fit[order(df$Demographic)])
lm.df$ymax = lm.df$Proficiency + lm.df$se
lm.df$ymin = lm.df$Proficiency - lm.df$se

现在我们准备绘图了,直接使用plotlyAPI

plot_ly() %>%
  add_trace(data=df, x=~Demographic, y=~Proficiency, type="scatter", mode="markers",
            size=~N.Tested, color=~N.Tested, colors = c("#8B1A1A", "#FFA500"), showlegend=F) %>%
  add_ribbons(data=lm.df, x=~Demographic, ymin = ~ymin, ymax = ~ymax,
              line = list(color="transparent"), showlegend=F,
              fillcolor = "#77777777") %>%
  add_trace(data=lm.df, x=~Demographic, y=~Proficiency, 
          type="scatter", mode="lines", line=list(color="black"), showlegend=F) 

您可以仅通过 geom_smooth 添加回归线,并使用 stat = "smooth" 通过 geom_ribbon 添加功能区。它增加了一个额外的步骤,但分离层允许您在不弄乱置信带的情况下为线条着色。

d <- c + geom_smooth(method = "lm", se = FALSE, color = "black")
e <- d + geom_ribbon(stat = "smooth", method = "lm", alpha = .15)
ggplotly(e)