简体   繁体   中英

Adjusting graphs with Matplotlib

I'm having some problems adjusting the font size of the numerical labels on y axis of my graphs. Adjusting the font size only seems to adjust the text in the legend box.

Adjusting the 'axes' doesn't work because I've used axes.ravel() to help give a 2x2 set of four subplots.

"axes.set_xlabel(fontsize='large', fontweight='bold') AttributeError: 'numpy.ndarray' object has no attribute 'set_xlabel'"

#The part of the code that creates the subplots.

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(40,20), squeeze=False, sharey=True)
axes = axes.ravel()

font = FontProperties()

font = {'weight' : 'bold','size'   : 22}

plt.rc('font', **font)

#Then under here are the loops that create each subplot.

for each_subplot in range(0,4):

    axes.set_xlabel(fontsize='large', fontweight='bold')

#Selecting the input data goes here, but I left it out.

axes itself is an array of axes. So you want to do:

for each_subplot in range(0,4):
    axes[each_subplot].set_xlabel(fontsize='large', fontweight='bold')

or simpler:

for ax in axes:
    ax.set_xlabel(fontsize='large', fontweight='bold')

axes is an ndarray now, so you need to extract the element from array and call set_xlabel() method on it. Try this.

for each_subplot in range(0,4):
    axes[each_subplot].set_xlabel(fontsize='large', fontweight='bold')

In such situations, I would personally recommend using enumerate which provides you access not only to the individual axis objects but also to the index which can be used to modify labels, for instance. To flatten the axes , you can either use axes.ravel() or axes.flatten() . Also, you can directly use axes.flatten() in the enumerate as shown below.

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8,5), squeeze=False, sharey=True)

for index, ax in enumerate(axes.ravel()):
    ax.set_xlabel('X-label %s' %index, fontsize='large', fontweight='bold')
plt.tight_layout()    

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM