簡體   English   中英

注釋在 matplotlib 子圖中消失

[英]Annotations disappear in matplotlib subplot

我從這個問題的答案中找到了以下方法來標記子圖中的行和列: Row and column headers in matplotlib's subplots 它工作得很好 - 對於一個空的 plot。 一旦我將數據添加到任何子圖中,該行和列的標簽就會消失。 我也為此嘗試了annotate解決方案,同樣的問題。 我不知道如何讓這些標簽不消失。 還有其他人有同樣的問題嗎? 解決方案的想法? (下面的代碼。)

(我正在使用 Jupyter 筆記本(.ipynb)。我認為這可能是問題所在,但我使用常規腳本(.py)對其進行了測試,但它也不起作用。)

工作代碼和output:

import matplotlib.pyplot as plt

cols = ['Column {}'.format(col) for col in range(1, 4)]
rows = ['Row {}'.format(row) for row in ['A', 'B', 'C', 'D']]

fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(12, 8))

for ax, col in zip(axes[0], cols):
    ax.set_title(col)
for ax, row in zip(axes[:,0], rows):
    ax.set_ylabel(row, size='large')

fig.tight_layout()
plt.show()

工作子圖

代碼不工作,output:

import matplotlib.pyplot as plt

cols = ['Column {}'.format(col) for col in range(1, 4)]
rows = ['Row {}'.format(row) for row in ['A','B','C','D']]

fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(12, 8))

for ax, col in zip(axes[0], cols):
    ax.set_title(col)
for ax, row in zip(axes[:,0], rows):
    ax.set_ylabel(row, size='large')

plt.subplot(431)
plt.scatter([1],[7]) #sample data

fig.tight_layout()
plt.show()

破碎的子圖

plt.subplot(431)在現有軸之上創建一個子圖,因此對特定 object 所做的所有自定義都將被刪除。 您需要將scatter function 應用到您希望顯示 plot 的軸上; 為此,您可以使用 軸 class

import matplotlib.pyplot as plt

cols = ['Column {}'.format(col) for col in range(1, 4)]
rows = ['Row {}'.format(row) for row in ['A','B','C','D']]

fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(12, 8))

for ax, col in zip(axes[0], cols):
    ax.set_title(col)
for ax, row in zip(axes[:,0], rows):
    ax.set_ylabel(row, size='large')

axes[0,0].scatter([1],[7]) #sample data

fig.tight_layout()
plt.show()

暫無
暫無

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

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