如何在 matplotlib 的循环中重复轴设置?

How to repeat axes setting in a loop in matplotlib?

我通常使用以下命令来创建多面板图:

import matplotlib.pyplot as plt

fig, mainax = plt.subplots(nrows=2, ncols=2, figsize=(10, 10), dpi=100)
ax1, ax2, ax3, ax4 = mainax.flatten()

然后,我使用以下命令调整坐标轴设置:

ax1.tick_params('x', which='major', length=10, width=2, direction='in', labelsize=24, labelbottom=True)

ax1.tick_params('x', which='minor', length=7, width=2, direction='in')

for axis in ['top', 'bottom', 'left', 'right']:
    ax1.spines[axis].set_linewidth(2)

for tick in ax1.get_xticklabels():
    tick.set_fontname('serif')

我必须为 ax1ax2ax3ax4 重复它们。只要我有几个面板,就没有问题,但是当我有太多面板时(例如,5 行和 4 列),如果我重复它们,代码会很难看。

如何将它们放在一个循环中? 或避免重复命令的任何替代方法?

您可以使用 matplotlib.rcParams 来避免任何循环。
您可以在 python 脚本的开头添加这些行:

rcParams['xtick.major.size'] = 10
rcParams['xtick.major.width'] = 2
rcParams['xtick.direction'] = 'in'
rcParams['xtick.labelsize'] = 24
rcParams['xtick.labelbottom'] = True

rcParams['xtick.minor.size'] = 7
rcParams['xtick.minor.width'] = 2

rcParams['font.family'] = 'serif'

rcParams['axes.linewidth'] = 2

有关更多自定义选项,请参阅 this documentation
工作代码示例:

import matplotlib.pyplot as plt
from matplotlib import rcParams

rcParams['xtick.major.size'] = 10
rcParams['xtick.major.width'] = 2
rcParams['xtick.direction'] = 'in'
rcParams['xtick.labelsize'] = 24
rcParams['xtick.labelbottom'] = True

rcParams['xtick.minor.size'] = 7
rcParams['xtick.minor.width'] = 2

rcParams['font.family'] = 'serif'

rcParams['axes.linewidth'] = 2


fig, mainax = plt.subplots(nrows=2, ncols=2, figsize=(10, 10), dpi=100)

plt.show()
  • 2行2列:

  • 5行4列: