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

Plotly双Y轴绘图折线图异常,如何保证折线与柱状图共用同一X轴

问题核心原因

  • 原始数据集未生成MonthName字段,无法和x轴配置中指定的month.name排序规则匹配,导致不同图层的x轴取值错位
  • y轴与对应数值范围绑定错误,数据超出坐标轴显示范围,导致折线消失或显示异常

修正方案

先给数据集新增和数字月份一一对应的月份名称字段,同时调整y轴范围和对应指标的绑定关系,初始绘图时统一指定全局x轴,后续所有图层默认复用同一个x轴即可:

library(plotly)
# 构造数据集,新增月份名称列
temprain<-data.frame(month = c(1:12), 
                     Train = c(250,220, 180,97,38,27,31,47,70,140,200,250), 
                     Tair = c(17,16, 15,13,9,6,5,9,12,13,14,16))
temprain$MonthName <- month.name[temprain$month]

# 定义两个指标的坐标轴范围
tempseq<-seq(0,20,by=0.5) # 气温数值范围
rainseq<-seq(0,260,by=1) # 降雨量数值范围

# x轴配置
xlab<-list(type = "category",
           categoryorder = "array",
           categoryarray = month.name,
           showgrid = TRUE,
           showline = TRUE,
           autorange = FALSE, # 关闭自动范围,保证按指定的月份顺序显示
           showticklabels = TRUE,
           ticks = "outside",
           tickangle = 0
)

# 绘图,初始调用统一指定x轴
plot_ly(temprain, x = ~MonthName) %>%
  add_bars(y = ~Train, type = "bar", name = "降雨量", yaxis = "y") %>%
  add_lines(y = ~Tair, name = "气温", yaxis = "y2") %>%
  layout(xaxis = xlab,
         yaxis = list(showline = TRUE, side = "left",
                      title = "降雨量(mm)", range = rainseq),
         yaxis2 = list(showline = TRUE, side = "right",
                       overlaying = "y",  title = "气温(℃)", range = tempseq),
         showlegend = TRUE,
         margin = list(pad = 0, b = 50, l = 50, r = 50))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:09:03