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

如何为pandas plot函数subplots模式下的子图设置不同xtick标签?

为Pandas子图设置独立X轴标签及调整子图间距

1. 为每个子图设置独立X轴刻度标签

生成子图后,可遍历返回的Axes对象列表与对应的标签列表,逐个为子图配置X轴刻度:

完整代码示例:

import pandas as pd
import matplotlib.pyplot as plt

# 创建数据集
data1 = {'col1': [10, 20, 30], 'col2': [20, 30, 40], 'col3': [40, 20, 10]}
df = pd.DataFrame(data1)

# 定义各子图的X轴日期标签
idxs = [pd.to_datetime(['2021-01-01', '2021-01-02', '2021-01-03']), 
        pd.to_datetime(['2022-04-04', '2022-04-05', '2022-04-06']), 
        pd.to_datetime(['2023-05-10', '2023-05-11', '2023-05-12'])]

# 生成子图
colors = ['red', 'blue', 'green']
ax1 = df.plot(subplots=True, sharex=False, figsize=(6, 8), color=colors)

# 逐个设置子图X轴刻度与标签
for ax, ticks in zip(ax1, idxs):
    ax.set_xticks(range(len(ticks)))  # 指定刻度位置
    ax.set_xticklabels(ticks.strftime('%Y-%m-%d'), rotation=45)  # 设置标签并旋转避免重叠

plt.tight_layout()
plt.show()

2. Pandas Plot中调整子图间距的参数

Pandas的plot函数没有直接的hspace参数,但可通过subplots_kws传递配置,借助matplotlib的gridspec_kw实现子图间距调整:

整合到绘图代码的示例:

ax1 = df.plot(subplots=True, sharex=False, figsize=(6, 8), color=colors,
              subplots_kws={'gridspec_kw': {'hspace': 0.5}})

也可在生成子图后直接调用matplotlib原生方法调整:

plt.subplots_adjust(hspace=0.5)

两种方式效果一致,前者是绘图时直接配置,后者是绘图后手动调整。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 14:31:00