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

如何为Matplotlib中所有子图统一设置相同的X轴格式?

解决Matplotlib批量设置子图X轴格式的问题

错误原因

你之前的遍历代码报错,是因为plt.subplots()会新建一个空白Figure和Axes数组,返回的是(Figure对象, Axes对象数组)的元组。你循环时拿到的fig是Figure对象,而xaxis是子图(Axes对象)的属性,所以触发AttributeError。

正确解决方案

步骤1:修正子图创建代码(避免变量覆盖)

你之前重复使用fig_ax_2变量,会覆盖之前的子图引用,先改成独立变量名,再把所有子图Axes对象收集到列表里:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# 假设你已定义widths和heights变量
widths = [1,1,1,1]
heights = [2,1]

# 创建子图
fg = plt.figure(figsize=(9, 4), constrained_layout=True)
gs = fg.add_gridspec(ncols=4, nrows=2, width_ratios=widths, height_ratios=heights)

# 逐个创建子图,变量名不重复
fig_ax_1 = fg.add_subplot(gs[0, :])
fig_ax_2 = fg.add_subplot(gs[1, 0])
fig_ax_3 = fg.add_subplot(gs[1, 1])
fig_ax_4 = fg.add_subplot(gs[1, 2])
fig_ax_5 = fg.add_subplot(gs[1, 3])

# 收集所有子图Axes到列表
all_axes = [fig_ax_1, fig_ax_2, fig_ax_3, fig_ax_4, fig_ax_5]

步骤2:批量应用X轴格式

直接遍历子图列表,对每个Axes对象设置格式:

# 遍历所有子图,应用自定义X轴格式
for ax in all_axes:
    ax.xaxis.set_major_locator(mdates.DayLocator())
    ax.xaxis.set_minor_locator(mdates.HourLocator(byhour=[6,12,18]))
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%d.%m"))
    ax.xaxis.set_minor_formatter(mdates.DateFormatter("%H"))
    ax.grid(which = "both", linewidth = 0.2)
    ax.tick_params(axis='x', which='minor', labelsize=8)

简化方式:直接获取Figure内的所有子图

如果不想手动收集子图,也可以用fg.get_axes()直接获取当前Figure里的所有Axes对象:

for ax in fg.get_axes():
    ax.xaxis.set_major_locator(mdates.DayLocator())
    ax.xaxis.set_minor_locator(mdates.HourLocator(byhour=[6,12,18]))
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%d.%m"))
    ax.xaxis.set_minor_formatter(mdates.DateFormatter("%H"))
    ax.grid(which = "both", linewidth = 0.2)
    ax.tick_params(axis='x', which='minor', labelsize=8)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 04:23:39