Matplotlib同图绘制堆叠柱状图与折线图时柱状图消失如何解决
问题原因
该问题的核心是两次绘图的X轴坐标体系不兼容:
dfa绘制堆叠柱状图时,pandas的柱状图接口会自动将分类时间索引转为整数位置坐标,3个日期对应X轴的0、1、2三个位置,仅将刻度标签显示为日期文本。- 后续用
dli绘制折线图时,pandas默认把datetime类型的索引当作数值型时间戳(对应1970年至今的累计秒/毫秒值)作为X轴坐标,该数值远大于0、1、2,会直接将X轴的显示范围拉伸到时间戳的数值区间,原本在0、1、2位置的堆叠柱状图被挤出可视范围,看起来就像消失了。
另外代码中额外加的secondary_y = True属于多余参数,你已经手动通过ax1.twinx()创建了次Y轴,保留该参数会额外新增第三根Y轴,加重坐标轴逻辑混乱。
解决方案
只需统一两次绘图的X轴坐标体系即可,以下是修正后的可运行代码:
import pandas as pd import matplotlib.pyplot as plt # 数据准备部分保持不变 dfa = pd.DataFrame({'time' : [pd.to_datetime('2021-01-01'), pd.to_datetime('2021-01-01'), pd.to_datetime('2021-01-02'), pd.to_datetime('2021-01-02'), pd.to_datetime('2021-01-03'), pd.to_datetime('2021-01-03'), ], 'group' : ['a','b','a','b','a','b'], 'value' : [1,2,3,2,5,5]}) dli = pd.DataFrame({'time' :[pd.to_datetime('2021-01-01'), pd.to_datetime('2021-01-02'), pd.to_datetime('2021-01-03')], 'value' : [100,200,50]}) fig, ax1 = plt.subplots(figsize=(12, 4)) ax2 = ax1.twinx() # 处理柱状图数据,保留统一索引 df_bar = dfa.set_index(['time','group']).unstack()['value'] # 绘制堆叠柱状图 df_bar.plot.bar(stacked = True, ax = ax1) # 折线图使用和柱状图完全对齐的X轴坐标 ax2.plot(range(len(df_bar)), dli['value'], color = 'red', linewidth = 4) # 配置折线图例 ax2.legend(['折线指标'], loc='upper right') plt.show()
如果希望继续使用pandas的plot接口绘制折线,也可以通过对齐两个数据集的索引实现:
# 对齐dli和柱状图数据的索引 dli_aligned = dli.set_index('time').reindex(df_bar.index) # 直接用pandas接口绘制折线 dli_aligned.plot(ax=ax2, color='red', linewidth=4, legend=False)
内容的提问来源于stack exchange,提问作者ℕʘʘḆḽḘ
相关产品推荐
相关产品推荐

