Reputation: 163
I usually use the following commands to create a multi-panel plot:
import matplotlib.pyplot as plt
fig, mainax = plt.subplots(nrows=2, ncols=2, figsize=(10, 10), dpi=100)
ax1, ax2, ax3, ax4 = mainax.flatten()
Then, I use the following command to adjust the axes setting:
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')
I have to repeat them for ax1
, ax2
, ax3
, and ax4
. As long as I have a few panels, there is no problem, but when I have too many panels (e.g., 5 rows and 4 columns) the code would be ugly if I repeat them.
How can I put them in a loop? Or any alternative way to avoid repeating the commands?
Upvotes: 1
Views: 403
Reputation: 12496
You can avoid any loop by using matplotlib.rcParams
.
You can add those line at the beginning of your python script:
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
Refer to this documentation for more customization options.
Example of working code:
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()
Upvotes: 1