Matplotlib:如何为每个子图添加 xlabel、标题 [英] Matplotlib: how to add xlabel, title to each subplot

查看:127
本文介绍了Matplotlib:如何为每个子图添加 xlabel、标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 plt.subplots 绘制多个热图.我发现的一个例子如下:

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'

我怎样才能使它正确?

谢谢大家对我的帮助!

推荐答案

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

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

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

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

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

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

您可以在api文档 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆