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

同一Axes绘制柱状图与折线图仅显示最后图形的问题排查

解决同一Axes上柱状图与折线图仅显示最后图形的问题

我之前也踩过这个坑!你遇到的问题核心原因是:pandas绘制柱状图时会自动将x轴设置为分类轴(categorical axis),而折线图默认使用基于索引的数值轴,两者的x轴刻度逻辑不匹配,导致折线图要么被柱状图完全覆盖,要么显示在可视化区域外,最终只看到最后绘制的图形。

下面是两种亲测有效的解决方案:

方案1:明确指定折线图的x轴位置

通过range(len(df_h))来对应柱状图的每个柱子的x坐标位置,确保两者对齐:

import matplotlib.pyplot as plt
import pandas as pd

# 示例数据(替换成你的df_h)
df_h = pd.DataFrame({
    'ActivePower': [200, 250, 180, 300, 220],
    # 如果有时间列也可以用它作为分类标签
    'Hour': ['00', '01', '02', '03', '04']
}).set_index('Hour')

colors = '#2ca02c'

# 先创建统一的Axes对象
fig, ax = plt.subplots(figsize=(16, 8))

# 绘制柱状图
df_h.plot(y='ActivePower', kind='bar', ax=ax, linewidth=2, color=colors)

# 绘制折线图,指定x为柱子的位置索引
df_h.plot(y='ActivePower', kind='line', ax=ax, marker='o', color='#ff7f0e', 
          x=range(len(df_h)), linewidth=3)

plt.title('ActivePower: Bar + Line Plot')
plt.tight_layout()
plt.show()

方案2:手动对齐折线图的x轴刻度

如果不想指定x参数,可以手动将折线图的x轴刻度设置为和柱状图一致的分类刻度:

ax = df_h.plot(y='ActivePower', kind='bar', figsize=(16,8), linewidth=2, color=colors)
# 绘制折线图到同一个Axes
line_ax = df_h.plot(y='ActivePower', kind='line', ax=ax, marker='s', color='#1f77b4', linewidth=3)

# 对齐x轴刻度:设置刻度位置为柱子的索引,标签为DataFrame的索引
line_ax.set_xticks(range(len(df_h)))
line_ax.set_xticklabels(df_h.index)

plt.tight_layout()
plt.show()

这两种方法都能让柱状图和折线图同时显示在同一个Axes上,核心就是让两者的x轴刻度位置完全匹配,避免因轴类型不一致导致的显示问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:02:21