簡體   English   中英

Matplotlib:如何為每個子圖添加 xlabel、標題

[英]Matplotlib: how to add xlabel, title to each subplot

我正在嘗試使用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'

我怎樣才能使它正確?

謝謝大家幫助我!!!

使用 matplotlib 面向對象的接口時,正確使用的命令是ax.set_xlabelax.set_ylabel

(將這些與狀態機接口的plt.xlabel等進行比較)。

同樣,要設置標題,您需要ax.set_title

您可以在此處的 api 文檔中查看axes實例的所有可用方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM