Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
841 views
in Technique[技术] by (71.8m points)

python - Matplotlib: how to add xlabel, title to each subplot

I'm trying to plot multiple heatmaps using the plt.subplots. An example I found is as follows:

import numpy as np
import matplotlib.pyplot as plt

# Generate some data that where each slice has a different range
# (The overall range is from 0 to 2)
data = np.random.random((4,10,10))
data *= np.array([0.5, 1.0, 1.5, 2.0])[:,None,None]

# Plot each slice as an independent subplot
fig, axes = plt.subplots(nrows=1, ncols=4,figsize=(12,3))
i=0
for dat, ax in zip(data, axes.flat):
    # The vmin and vmax arguments specify the color limits
    im = ax.imshow(dat, vmin=0, vmax=2,cmap='Reds')
    # ax.xlabel(str(i))
    # ax.ylabel(str(i))
    i += 1

# Make an axis for the colorbar on the right side
cax = fig.add_axes([0.95, 0.155, 0.03, 0.67])
fig.colorbar(im, cax=cax)

figtype = 'jpg'
fig.savefig('aaa.jpg',format = figtype,bbox_inches='tight')
fig.tight_layout()

The code succeeds if I comment the following two lines (which is done in the above example):

ax.xlabel(str(i))
ax.ylabel(str(i))

If I use the two lines, I get errors saying:

AttributeError: 'AxesSubplot' object has no attribute 'xlabel'

How can I make it correct?

Thank you all for helping me!!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When using the matplotlib object-oriented interface, the correct commands to use are ax.set_xlabel and ax.set_ylabel.

(Compare these to plt.xlabel, etc., for the state-machine interface).

Likewise, to set a title, you need ax.set_title

You can see all the available methods for an axes instance in the api docs, here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...