对所有子图应用相同的轴格式

问题描述 投票:0回答:1

我在图中构建了 5 个子图,以便较大的子图Fig_1 占据图中的[rows_0, cols_0:3],较小的子图fig_2-fig_5 占据图中的[rows_1, cols_0-cols_3]。

我怎样才能一次将相同的x轴格式应用于图中列出的所有无花果?或者也许我可以迭代子块,一次应用一个格式,但我找不到方法来做到这一点。

# creating sublots
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, :])
       # plotting
       # here I must add axis format (see below) and repeat this after each fig
fig_ax_2 = fg.add_subplot(gs[1, 0])
       # plotting
       # axis format (see below)
fig_ax_2 = fg.add_subplot(gs[1, 1])
       # plotting
       # axis format (see below)
fig_ax_2 = fg.add_subplot(gs[1, 2])
       # plotting
       # axis format (see below)
fig_ax_2 = fg.add_subplot(gs[1, 3])
       # plotting
       # axis format (see below)


#custom axis format I need to apply to all figs
fig_ax_1.xaxis.set_major_locator(mdates.DayLocator())          # fig_ax_2 for smaller figs
fig_ax_1.xaxis.set_minor_locator(mdates.HourLocator(byhour=[6,12,18]))
fig_ax_1.xaxis.set_major_formatter(mdates.DateFormatter("%d.%m"))
fig_ax_1.xaxis.set_minor_formatter(mdates.DateFormatter("%H"))
fig_ax_1.grid(which = "both",linewidth = 0.2)
fig_ax_1.tick_params(axis='x', which='minor', labelsize=8)

我尝试过类似以下的操作,但它给了我 AttributeError: 'Figure' object has no attribute 'xaxis'

for fig in plt.subplots():    # also tried plt.subplots()[1:], this just creates empty Figure 2, leaving my Figure intact
        fig.xaxis.set_major_locator(mdates.DayLocator())
        fig.xaxis.set_minor_locator(mdates.HourLocator(byhour=[6, 12, 18]))
        fig.xaxis.set_major_formatter(mdates.DateFormatter("%d.%m"))
        fig.xaxis.set_minor_formatter(mdates.DateFormatter("%H"))
        fig.grid(which="both", linewidth=0.2)
        fig.tick_params(axis='x', which='minor', labelsize=8)
python matplotlib plot format axis
1个回答
0
投票

我认为您混淆了

Figure
Axes
。你可以循环播放
fg.axes
:

for ax in fg.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)
© www.soinside.com 2019 - 2024. All rights reserved.