Plotly离散轴场景下水平条形图添加全高垂直线实现问题
解决方法
直接使用Plotly原生的layout.shapes配置实现跨整个绘图区的垂直线,不受Y轴是离散类型的限制,不需要额外添加scatter轨迹。
修改后的完整代码如下:
library(plotly) library(tidyverse) df <- tribble( ~region , ~status , 'Reg 1' , 10000 , 'Reg 2' , 20000 , 'Reg 3' , 15000 ) target <- 17000 plot_ly(df , orientation = 'h') %>% add_bars(x = ~status , y = ~region , text = ~status , textposition = 'inside') %>% layout(showlegend = FALSE , # 垂直线核心配置 shapes = list( list( type = "line", x0 = target, x1 = target, y0 = 0, y1 = 1, # y轴使用绘图区相对坐标,不受离散轴取值限制 yref = "paper", line = list(color = "darkred") ) ), annotations = list(text = paste('Target:\n' , target) , xref = 'x' , yref = 'paper' , x = target , y = 0.90 , xanchor = 'left' , yanchor = 'top' , showarrow = FALSE , font = list(color = 'darkred')))
关键参数说明:
shapes是Plotly原生的绘图元素配置项,优先级高于轨迹层,不需要依赖额外的trace实现辅助线yref = "paper"指定Y轴坐标使用绘图区的相对比例,0对应绘图区最底部、1对应最顶部,完全不受Y轴是离散/连续类型、类别数量多少的影响- 线的x0和x1都设为目标值,即可得到垂直于X轴的直线,上下贯穿整个绘图区域
内容的提问来源于stack exchange,提问作者bthebread
相关产品推荐
相关产品推荐

