简体   繁体   中英

How to index a Matplotlib subplot

Im trying to plot two piecharts together. I have been reading the Matplotlib documentation https://matplotlib.org/stable/gallery/pie_and_polar_charts/pie_demo2.htmland cannot see what im doing wrong. I'm getting an indexing error in line 13 (patches = axs[1,1].pie...)

The code worked until I started using the axs[1,1] etc and tried to have the subplots.

Code

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

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

Array axs is 1-dimensional, change axs[1,1] and axs[1,2] to axs[0] and axs[1] , then your code will work.

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

So your axs is just a numpy array of shape (2,).

changing the index should do the trick.

Change axs[1,1] --> axs[0] , axs[1,2]--> axs[1]

The problem is that Matplotlib squeezes the axs array into a 1D shape if there is only one row or only one column of subplots. Fortunately, this inconsistent bahaviour can be disabled by passing the squeeze argument:

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

And then you can just normally index into it with axs[0,0] and axs[0,1] , like you would if there were multiple rows of subplots.

I would recommend to always pass squeeze=False , so that the behaviour is the same regardless of how many rows there are and automated plotting scripts don't need to come up with special cases for single-row plots (or else risk cryptic errors if somebody later on wants to generate a plot that happens to have only a single row).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM