【问题标题】:How to index a Matplotlib subplot如何索引 Matplotlib 子图
【发布时间】:2021-06-28 06:22:54
【问题描述】:

我正在尝试将两个饼图绘制在一起。我一直在阅读 Matplotlib 文档 https://matplotlib.org/stable/gallery/pie_and_polar_charts/pie_demo2.htmland 看不到我做错了什么。我在第 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

【问题讨论】:

    标签: python matplotlib subplot axes


    【解决方案1】:

    数组axs 是一维的,将axs[1,1]axs[1,2] 更改为axs[0]axs[1],那么你的代码就可以工作了。

    【讨论】:

      【解决方案2】:

      来自 matplotlib documentation

      # 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)
      

      所以你的axs 只是一个形状为 (2,) 的 numpy 数组。

      更改索引应该可以解决问题。

      更改axs[1,1] --&gt; axs[0]axs[1,2]--&gt; axs[1]

      【讨论】:

        猜你喜欢
        • 2019-06-07
        • 2019-10-22
        • 1970-01-01
        • 2011-03-24
        • 2017-04-23
        • 1970-01-01
        • 1970-01-01
        • 2020-07-14
        • 2016-06-01
        相关资源
        最近更新 更多