首页 > 解决方案 > Plotly 中的 Add_Trace 问题

问题描述

如何增加绿线 (lcl) 和红线 (lsl) 的长度,以便它们在add_trace函数中延伸到绘图的末尾(而不是中途停止)? 在此处输入图像描述

这是我的图表代码:

      output$p <- renderPlotly({
plot1 %>%

                add_trace(y = lcl(),type = "scatter", mode = "lines", line = list(color = 'lightgreen', width = 2, dash = 'solid'), inherit = FALSE, name = paste("LCL =", lcl()[1])) %>%
     
                add_trace(y = lsl(),type = "scatter", mode = "lines", line = list(color = 'red', width = 2, dash = 'solid'), inherit = FALSE, name = paste("LSL =", lsl()[1])) %>%
              %>%
                layout(
                    title = paste(" cell culture", input$select),
                    yaxis = list(  showline = TRUE,
                                   mirror = "ticks",
                                   linecolor = toRGB("grey"),
                                   linewidth = 1.85
                    ),
                    xaxis = list(  showline = TRUE,
                                   mirror = "ticks",
                                   linecolor = toRGB("grey"),
                                   linewidth = 1.85,
                                   tickangle=70))
        })

编辑:为简单起见,我去掉了实际绘图(散点图)的代码,该图很好,不需要任何调整。

标签: rplotlyr-plotly

解决方案


我不会使用add_trace创建跨越整个图形的水平线,而是将水平线作为形状添加到布局中:

layout(shapes = list(
  list(
    type = "line",
    x0 = 0,
    x1 = 1,
    xref = "paper",
    y0 = 75,
    y1 = 75,
    line = list(color = 'lightgreen', width = 2)
  ),
  list(
    type = "line",
    x0 = 0,
    x1 = 1,
    xref = "paper",
    y0 = 100,
    y1 = 100,
    line = list(color = 'red', width = 2)
  )
))

xref = "paper"使用,因此该线跨越整个图形。

纸张坐标中的定位不是以绝对像素术语进行的,而是以相对于坐标系的术语进行的,该坐标系由 (layout.margin.l, layout.margin.b) 处的原点 (0,0) 和点 (1, 1)在(layout.width-layout.margin.r,layout.height-layout.margin.t)...

https://plotly.com/python/figure-structure/#positioning-with-paper-container-coordinates-or-axis-domain-coordinates

y根据您的要求更改值。


推荐阅读