繁体   English   中英

使用 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")返回:

在此处输入图片说明

有没有一种简单的方法可以摆脱边界线,但保持主线黑色?

编辑:我无法提供带有数据的完整代码,但提供了会在此处重现错误的情况。 您只需要回答这个问题即可。 根据下面的评论,它可能与 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经常给出意想不到的结果。 如果您想要的最终产品是绘图图,那么通常最好直接使用绘图 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

现在我们准备好绘图了,直接使用 plotly API

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 ,并通过增加色带geom_ribbon使用stat = "smooth" 它增加了一个额外的步骤,但分离图层可以让您在不弄乱置信度带的情况下为线条着色。

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

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM