pythonmatplotlibplotformataxis

Applying identical axis format to all subplots


I'm building 5 subplots in a Figure, so that the larger sublot fig_1 occupies [rows_0, cols_0:3] of the Figure, and smaller sublots fig_2-fig_5 occupy [rows_1, cols_0-cols_3] of the Figure.

How could I apply an identical x-axis format to all of the listed figs in the Figure at once? Or maybe I could iterate over the sublots, to apply the format one at a time, but I can't find a way to do this.

# 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)

I've tried something like the following, but it gives me 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)

Solution

  • I think you're confusing a Figure and an Axes. You could just loop over 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)