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

如何在R的plotly分类水平条形图中添加垂直虚线

问题修正方案

你遇到的三个警告分别对应三处代码问题,按以下规则修改即可消除警告:

  • 全局plot_ly()中定义的marker参数会作用于所有trace,而后续线条trace仅使用lines模式,因此需要把marker参数移入add_bars()内部
  • add_trace未显式指定trace类型,需补充type = 'scatter'参数
  • y轴为离散类别轴,你给垂直虚线配置的数值型y值会触发轴类型冲突,将虚线的y值改为离散轴的类别范围即可
  • 水平条形的orientation = 'h'参数属于图层配置,需放在add_bars()内而非全局layout中

修正后可运行代码

library(plotly)
library(dplyr)

df <- data.frame(x = c(5,7), y = c("A","B"), bar.width = rep(0.1,2))

plot_ly(data=df) %>%
  add_bars(x=~x,y=~y,width=~bar.width, orientation='h', marker=list(color="darkred")) %>%
  layout(xaxis=list(title="X"),yaxis=list(title=NA)) %>%
  add_trace(type = 'scatter', x=c(2.5,2.5), y=c("A","B"), mode="lines", showlegend=F, line=list(color="black",dash='dash'))

运行上述代码即可正常生成带垂直虚线的水平条形图,无警告输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:21:03