如何为每个子图添加x轴标签和标题

7
我正在尝试使用plt.subplots绘制多个热力图。我找到的一个示例如下:
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()

如果我注释掉以下两行代码(就像上面的例子中所做的那样),那么代码就会成功运行。
ax.xlabel(str(i))
ax.ylabel(str(i))

如果我使用这两行,就会出现错误信息:“
AttributeError: 'AxesSubplot' object has no attribute 'xlabel'

怎样才能把它弄对呢?
1个回答

20

当使用matplotlib面向对象的接口时,正确的命令是 ax.set_xlabelax.set_ylabel

(与状态机接口中的 plt.xlabel 等进行比较)

同样,要设置标题,需要使用 ax.set_title

可以在api文档这里中查看axes实例的所有可用方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接