[英]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.