【问题标题】:Add error bars to points within a plotly box plot将误差线添加到绘图箱图中的点
【发布时间】:2025-12-11 09:10:02
【问题描述】:

我正在为这些数据创建一个Rplotlyboxplot

set.seed(1)
df <- data.frame(value = rnorm(100),
                 value.error. = runif(100,0.01,0.1), 
                 treatment = rep(LETTERS[1:10], 10), 
                 replicate = rep(1:10, 10), stringsAsFactors = F)
df$treatment <- factor(df$treatment)

在每个框中,我将复制品添加为点:

library(dplyr)
plotly::plot_ly(x = df$treatment, split = df$treatment, y = df$value, 
                type = "box", showlegend = F, color = df$treatment,
                boxpoints = F, fillcolor = 'white') %>%
  plotly::add_trace(x = df$treatment, y = df$value, type = 'scatter', mode = "markers", 
                    marker = list(size = 8), showlegend = F, color = df$treatment)

这给出了:

现在我想为每个点添加垂直误差线(根据df$value.error)。

这个:

plotly::plot_ly(x = df$treatment, split = df$treatment, y = df$value,
                type = "box", showlegend = F, color = df$treatment, 
                boxpoints = F, fillcolor = 'white') %>%
  plotly::add_trace(x = df$treatment, y = df$value, type = 'scatter', mode = "markers", 
                    marker = list(size = 8), showlegend = F, color = df$treatment) %>%
  plotly::add_trace(error_y = list(array = df$sd), showlegend = F)

给了我上面相同的情节。

但是,如果我只绘制点并使用以下方法添加它们的错误:

plotly::plot_ly(x = df$treatment, y = df$value, 
                type = 'scatter', mode = "markers", 
                marker = list(size = 8), showlegend = F, color = df$treatment) %>%
  plotly::add_trace(error_y =list(array = df$sd), showlegend = F)

我确实得到了带有垂直误差线的点:

所以我的问题是如何让框 + 点 + 误差线工作? 而且,如果解决方案还可以将抖动点与其误差线结合起来,那就更好了。

【问题讨论】:

    标签: r plotly boxplot r-plotly errorbar


    【解决方案1】:

    您可以在绘制点和误差线后添加箱线图。

    library(plotly)
    
    plot_ly(data = df,
            x = ~treatment, y = ~value, 
            type = 'scatter', mode = "markers", 
            marker = list(size = 8), showlegend = F, color = df$treatment) %>%
      add_trace(error_y =list(array = ~value.error.), showlegend = F) %>% 
      add_boxplot(x = ~treatment, split = ~treatment, y = ~value, 
                  showlegend = F, color = ~treatment,
                  boxpoints = F, fillcolor = 'white')
    

    数据:

    
    set.seed(1)
    df <- data.frame(value = rnorm(100), 
                     value.error. = runif(100,0.01,0.1), 
                     treatment = rep(LETTERS[1:10], 10), 
                     replicate = rep(1:10, 10), 
                     stringsAsFactors = F)
    df$treatment <- factor(df$treatment)
    

    【讨论】: