簡體   English   中英

如何索引 Matplotlib 子圖

[英]How to index a Matplotlib subplot

我正在嘗試將 plot 兩個餅圖放在一起。 我一直在閱讀 Matplotlib 文檔https://matplotlib.org/stable/gallery/pie_and_polar_charts/pie_demo2.html並且看不出我做錯了什么。 我在第 13 行遇到索引錯誤 (patches = axs[1,1].pie...)

在我開始使用 axs[1,1] 等並嘗試使用子圖之前,代碼一直有效。

代碼

import matplotlib.pyplot as plt
from matplotlib import rcParams

print('\n'*10)

# Make figure and axes
fig, axs = plt.subplots(1,2)

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Alpha', 'Beta', 'Gamma', 'Phi', 'Theta'
sizes = [3, 6, 2, 3, 10]
explode = (0, 0.1, 0, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')
patches = axs[1,1].pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)[0]
#patches[2].set_hatch('\\\\')  # Pie slice #0 hatched.
axs[1,1].axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.title("My title", fontsize=14, fontweight='bold', size=16, y=1.02)
 



# Pie chart 2
labels = 'Alpha', 'Beta', 'Gamma', 'Phi', 'Theta'
sizes = [3, 6, 2, 3, 10]
explode = (0, 0.1, 0, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')
patches = axs[1,2].pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)[0]
patches[2].set_hatch('\\\\')  # Pie slice #0 hatched.
axs[1,2].axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.title("My title", fontsize=14, fontweight='bold', size=16, y=1.02)
 

plt.show()

追溯

Traceback (most recent call last):
  File "/Users/.../Desktop/WORK/time_1.py", line 13, in <module>
    patches = axs[1,1].pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

數組axs是一維的,將axs[1,1]axs[1,2]更改為axs[0]axs[1] ,然后您的代碼將起作用。

來自 matplotlib 文檔

# using the variable ax for single a Axes
fig, ax = plt.subplots()

# using the variable axs for multiple Axes
fig, axs = plt.subplots(2, 2)

# using tuple unpacking for multiple Axes
fig, (ax1, ax2) = plt.subplots(1, 2)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

所以你的斧頭只是一個形狀為 (2,) 的axs數組。

更改索引應該可以解決問題。

更改axs[1,1] --> axs[0]axs[1,2]--> axs[1]

問題是如果只有一行或只有一列子圖,Matplotlib 會將axs數組壓縮成一維形狀。 幸運的是,可以通過傳遞squeeze參數來禁用這種不一致的行為:

fig, axs = plt.subplots(1, 2, squeeze=False)

然后您通常可以使用axs[0,0]axs[0,1]對其進行索引,就像有多行子圖一樣。

我建議始終傳遞squeeze=False ,這樣無論有多少行,行為都是相同的,並且自動繪圖腳本不需要為單行圖提出特殊情況(否則可能會出現神秘錯誤,如果后來有人想生成一個 plot,它恰好只有一行)。

暫無
暫無

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

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