我在一个图中构建了5个子图,这样较大的子图fig_1占据了图的[rows_0,cols_0:3],较小的子图fig_2—fig_5占据了图的[rows_1,cols_0—cols_3].

How could I apply an identical x-axis format to all of the listed figs in the Figure at once?或者也许我可以在子地段上重复一遍,一次一个地应用格式,但是我找不到这样的方法.

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

推荐答案

我觉得你把FigureAxes搞混了.你可以在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)

Python相关问答推荐

Python:在类对象内的字典中更改所有键的索引,而不是仅更改一个键

Django管理面板显示字段最大长度而不是字段名称

试图找到Python方法来部分填充numpy数组

删除最后一个pip安装的包

如何在python polars中停止otherate(),当使用when()表达式时?

如何启动下载并在不击中磁盘的情况下呈现响应?

为什么np. exp(1000)给出溢出警告,而np. exp(—100000)没有给出下溢警告?

如何使用使用来自其他列的值的公式更新一个rabrame列?

为什么我的sundaram筛这么低效

为什么Python内存中的列表大小与文档不匹配?

如何根据rame中的列值分别分组值

语法错误:文档. evaluate:表达式不是合法表达式

为用户输入的整数查找根/幂整数对的Python练习

一个telegram 机器人应该发送一个测验如何做?""

在Django中重命名我的表后,旧表中的项目不会被移动或删除

SpaCy:Regex模式在基于规则的匹配器中不起作用

利用SCIPY沿第一轴对数组进行内插

如何在Polars中将列表中的新列添加到现有的数据帧中?

如何在Polars中处理用户自定义函数的多行结果?

将时间序列附加到数据帧