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

两个pandas Series绘图如何实现共享X轴上下堆叠排布

问题原因

你当前代码的问题出在pandas的plot()方法默认行为:如果没有显式传入ax参数指定绘图的坐标轴,第二次调用y.plot()时会直接在当前活跃的第一个坐标轴(也就是你第一次x.plot()生成的ax)上绘图,所以两条线会叠加在同一张图里,后续的sharex调用自然也没有效果。

实现堆叠共享X轴的方案

你可以先通过matplotlib创建2行1列的子图并预先设置共享X轴,再分别指定每个Series的绘图轴即可,pandas的plot()方法支持传入ax参数绑定绘图位置,符合你用ax句柄实现需求的要求。

完整可运行代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

n=10
x = pd.Series(data = np.random.randint(0,10, n), index=pd.date_range(pd.to_datetime('today'), freq='D', periods=n))
y = pd.Series(data = np.random.randint(0,10, n), index=pd.date_range(pd.to_datetime('today'), freq='D', periods=n))

# 创建2行1列的堆叠子图,提前设置共享X轴
fig, (ax_top, ax_bottom) = plt.subplots(nrows=2, ncols=1, sharex=True, figsize=(7,5))

# 分别将两个Series绘制到对应坐标轴
x.plot(ax=ax_top, label='X序列')
y.plot(ax=ax_bottom, label='Y序列', color='orange')

# 可选配置:添加标签、图例等
ax_top.set_ylabel('X数值')
ax_top.legend()
ax_bottom.set_ylabel('Y数值')
ax_bottom.set_xlabel('日期')
ax_bottom.legend()

# 自动调整布局避免遮挡
plt.tight_layout()
plt.show()

运行后就会得到上下堆叠、X轴完全共享的两张折线图,X轴刻度只会在最下方的图中显示,避免重复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:27:05