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

带时间戳索引DataFrame双轴可视化:柱状图叠加折线图失败

解决柱状图+次坐标轴折线图不显示的问题

问题根源:pandas绘制柱状图时,会将时间戳索引转换为离散的类别型坐标轴,而后续调用secondary_y=True绘制折线图时,折线图的x轴数据是原始时间戳,和柱状图的类别x轴不匹配,导致折线图无法正常显示。

下面是两种可行的解决方法:

方法一:手动对齐x轴位置(推荐)

通过获取柱状图的柱子位置,将折线图的x轴数据替换为这些位置,实现坐标轴对齐:

import matplotlib.pyplot as plt

# 绘制主坐标轴的柱状图
ax1 = df[ts1:ts2].plot(y='A', kind='bar')
# 获取每个柱子的中心位置,作为折线图的x轴坐标
x_positions = [patch.get_x() + patch.get_width()/2 for patch in ax1.patches]
# 提取折线图的y值数据
y_data = df2[ts1:ts2]['B'].values

# 创建次坐标轴并绘制折线
ax2 = ax1.twinx()
ax2.plot(x_positions, y_data, color='#ff7f0e', marker='o', label='B')

# 补充图表元素
ax1.set_ylabel('A')
ax2.set_ylabel('B')
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')
plt.show()

方法二:利用pandas绘图的x参数指定位置

如果两个DataFrame的时间戳区间完全一致(行数相同),可以直接用柱状图的x轴刻度位置来绘制折线图:

import matplotlib.pyplot as plt

ax = df[ts1:ts2].plot(y='A', kind='bar')
# 获取柱状图的x轴刻度位置,传递给折线图的x参数
df2[ts1:ts2].plot(y='B', ax=ax, secondary_y=True, x=ax.get_xticks(), kind='line')

ax.set_ylabel('A')
ax.right_ax.set_ylabel('B')
plt.show()

注意:两种方法都要求df[ts1:ts2]和df2[ts1:ts2]的行数完全一致,否则会出现长度不匹配的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 04:29:58