Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix 'numpy.ndarray' object has no attribute 'get_figure' when plotting subplots

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?

like image 326
Ishan Dutta Avatar asked Oct 06 '20 16:10

Ishan Dutta


People also ask

How do I fix NumPy Ndarray object has no attribute append?

We can resolve this error by using the numpy. append() method provided by the NumPy library. The numpy. append() method returns a copy of an array with values appended to the specified axis.

How do I fix NumPy Ndarray?

The 'numpy. ndarray' object is not callable error occurs when you try to access the NumPy array as a function using the round brackets () instead of square brackets [] to retrieve the array elements. To fix this issue, use an array indexer with square brackets to access the elements of the array.

What is Ndarray object of NumPy module?

ndarray. An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.)


1 Answers

  • 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)
  • Unpack all of the subplot arrays from axes, using axes.ravel().
    • numpy.ravel, which returns a flattened array.
    • A list comprehension will also work, axe = [sub for x in axes for sub in x]
    • In practical terms, axes.ravel(), axes.flat, and axes.flatten(), can be used similarly. See What is the difference between flatten and ravel functions in numpy? & numpy difference between flat and ravel().
  • Assign each plot to one of the subplots in axe.
  • How to resolve AttributeError: 'numpy.ndarray' object has no attribute 'get_figure' when plotting subplots is a similar issue.
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

like image 109
Trenton McKinney Avatar answered Nov 15 '22 08:11

Trenton McKinney