簡體   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