9

I have written the following code to plot 6 pie charts in different subplots, but I get an error. This code works correctly if I use it to plot only 2 charts, but produces an an error for anything more than that.

I have 6 categorical variables in my dataset, the names of which are stored in the list cat_cols. The charts are to be plotted from the training data train.

CODE

fig, axes = plt.subplots(2, 3, figsize=(24, 10))
for i, c in enumerate(cat_cols):
 
 train[c].value_counts()[::-1].plot(kind = 'pie', ax=axes[i], title=c, autopct='%.0f', fontsize=18)
 axes[i].set_ylabel('')
 
plt.tight_layout()

ERROR

AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'

How do we rectify this?

Trenton McKinney
63.1k41 gold badges169 silver badges210 bronze badges
asked Oct 6, 2020 at 16:20
0

1 Answer 1

20
  • The issue is plt.subplots(2, 3, figsize=(24, 10)) creates two groups of 3 subplots, not one group of six subplots.
array([[<AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>],
 [<AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>]], dtype=object)
import pandas as pd
import numpy as np
# sinusoidal sample data
sample_length = range(1, 6+1)
rads = np.arange(0, 2*np.pi, 0.01)
data = np.array([np.sin(t*rads) for t in sample_length])
df = pd.DataFrame(data.T, index=pd.Series(rads.tolist(), name='radians'), columns=[f'freq: {i}x' for i in sample_length])
# crate the figure and axes
fig, axes = plt.subplots(2, 3, figsize=(24, 10))
# unpack all the axes subplots
axe = axes.ravel()
# assign the plot to each subplot in axe
for i, c in enumerate(df.columns):
 df[c].plot(ax=axe[i])

enter image description here

answered Oct 6, 2020 at 16:37
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.