You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny搭配Plotly绘制散点图无法显示误差棒的问题求助

代码错误点
  • 核心错误是数值列被转为字符类型:你使用sprintf()对sigma和c-e两列做格式化时,sprintf()返回的是字符串类型,同时cbind()拼接不同类型列时只要存在字符串列,所有列都会被强制转为字符类型,而Plotly的误差棒配置要求传入数值型数组做计算,字符型数据无法被识别,因此误差棒无法正常渲染。
  • 次要问题:没有保留原始数值列用于绘图计算,提前格式化的操作只适合用于悬浮提示等展示场景,不应该作用于参与绘图计算的字段。
修正方案

保留原始数值列用于绘图计算,单独生成格式化后的字段做展示使用,参考修正代码如下:

data = reactiveVal()

observe({
    results <- data.frame() # 实际数据源

    final.results <- data.frame(
        "id" = paste(results$a, results$b, results$c, sep = '-'),
        "sigma" = results$s, # 保留数值型用于误差计算
        "sigma_display" = sprintf("%.5g", results$s), # 格式化字段仅用于展示
        "c-e" = results$calc - results$exp, # 保留数值型用于x轴计算
        "ce_display" = sprintf("%.3g",results$calc - results$exp),
        check.names = FALSE # 避免列名`c-e`被自动转义
    )
    
    data(final.results)
})

output$plot <- renderPlotly(
    data() %>% plot_ly(
        x = ~`c-e`,
        y = ~id,
        height = 800,
        type = 'scatter', 
        mode = 'markers', 
        marker = list(color = "#90AFD9"),
        # 自定义悬浮提示使用格式化后的字段
        text = ~paste0("ID: ", id, "<br>计算-实验值: ", ce_display, "<br>误差: ", sigma_display),
        error_x = list(array = ~sigma, color = "#000000", type = "data")
    )
)

如果需要保留原有数据结构,也可以在绘图前将对应字段强制转为数值型:

output$plot <- renderPlotly(
    as.data.frame(data()[,c("id", "c-e", "sigma")]) %>% 
    mutate(`c-e` = as.numeric(`c-e`), sigma = as.numeric(sigma)) %>%
    plot_ly(
        x = ~`c-e`,
        y = ~id,
        height = 800,
        type = 'scatter', 
        mode = 'markers', 
        marker = list(color = "#90AFD9"),
        error_x = list(array = ~sigma, color = "#000000", type = "data")
    )
)

内容的提问来源于stack exchange,提问作者gregseth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 19:36:04