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

如何在R语言Plotly绘图中为最值标记点添加垂直线?

在R Plotly中添加连接最小值与最大值的垂直线

你可以使用Plotly的add_segments()函数实现这个需求,它能针对每个x轴位置,绘制一条从最小值点到最大值点的垂直线。以下是修改后的完整代码:

set.seed(123) # 设置随机种子保证结果可复现
maximum <- rnorm(30, mean = 20)
datasource <- rnorm(30, mean = 15)
minimum <- rnorm(30, mean = 10)
x <- c(1:30)

data <- data.frame(x,datasource,maximum,minimum)

fig <- plot_ly(data, x = ~x, y = ~datasource, name = 'trace 1', type = 'scatter', mode = 'lines+markers', marker = list(size = 10))
fig <- fig %>% add_trace(y = ~maximum, name = 'maximum', mode = 'markers', marker = list(size = 10))
fig <- fig %>% add_trace(y = ~minimum, name = 'minimum', mode = 'markers', marker = list(size = 10)) 

# 添加连接最小值与最大值的垂直线
fig <- fig %>% add_segments(
  x = ~x, xend = ~x,  # x轴起点和终点相同,保证是垂直线
  y = ~minimum, yend = ~maximum,  # y轴从最小值到最大值
  color = I("gray"),  # 设置线条颜色为灰色,避免和其他轨迹冲突
  name = "Range"  # 图例名称
)

fig <- fig %>% layout(title = "XBAR CHART",
                      xaxis = list(title = "ID"),
                      yaxis = list (title = "Measurement Value (mm)"))
fig

关键说明:

  • add_segments()通过绑定相同的x和xend值,确保每条线垂直于x轴;
  • y和yend分别关联最小值和最大值列,实现两点间的垂直连接;
  • 自定义线条颜色和图例名称,让图表层次更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:20:31