[英]How to draw multiple filled confidence bands on one plot using R plotly
我已嘗試使用以下代碼在一個圖上繪制兩個填充帶,但plotly
未在正確的一對線之間填充。 這樣做的正確方法是什么?
我也很感激知道如何指定處理兩個波段重疊的理想透明度。
require(plotly)
x <- c(1, 2, 1, 2)
g <- c('a','a','b','b')
y <- c(1, 2, 3, 4)
lo <- y - .1
hi <- y + .1
a <- plot_ly(x=x, y=y, group=g)
a <- add_trace(a, x=x, y=lo, group=g, fill='tonexty')
a <- add_trace(a, x=x, y=hi, group=g)
a
fill = "tonexty"
根據它之前出現的痕跡進行填充。 因此,使每個組從 hi 填充到 lo 的一種方法是顯式排序調用:
a <- plot_ly(x=x, y=y, group=g)
a <- add_trace(a, x = x[g=="a"], y = lo[g=="a"], group = g[g=="a"])
a <- add_trace(a, x = x[g=="a"], y = hi[g=="a"], group = g[g=="a"], fill = 'tonexty')
a <- add_trace(a, x = x[g=="b"], y = lo[g=="b"], group = g[g=="b"])
a <- add_trace(a, x = x[g=="b"], y = hi[g=="b"], group = g[g=="b"], fill = 'tonexty')
指定透明度的一種方法是使用toRGB
a <- plot_ly(x=x, y=y, group=g)
a <- add_trace(a, x = x[g=="a"], y = lo[g=="a"], group = g[g=="a"])
a <- add_trace(a, x = x[g=="a"], y = hi[g=="a"], group = g[g=="a"], fill = 'tonexty',
fillcolor = toRGB("red", 0.1))
a <- add_trace(a, x = x[g=="b"], y = lo[g=="b"], group = g[g=="b"])
a <- add_trace(a, x = x[g=="b"], y = hi[g=="b"], group = g[g=="b"], fill = 'tonexty',
fillcolor = toRGB("blue", 0.7))
a
x <- c(1, 2, 1, 2)
g <- c('a','a','b','b')
y <- c(1, 2, 3, 4)
lo <- y - .1
hi <- y + .1
df <- cbind.data.frame(x,y,g,lo,hi)
g.uni <- unique(df$g)
fig <- df %>%
plot_ly(type = "scatter",
mode = "lines",
showlegend = FALSE)
for(i in g.uni){
fig <- fig %>%
add_fun(function(plot) {
plot %>%
filter(g == i) %>%
add_ribbons(x = ~x,
ymin = ~lo,
ymax = ~hi
) %>%
add_lines(
x = ~x,
y = ~y,
line = list(
color = "black",
dash = "dot"
)
)
}
)
}
print(fig)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.