Skip to content
Advertisement

Bar chart plotting issue: TypeError: ‘AxesSubplot’ object is not iterable

Below shown is the categorical data detail for the bar chart, which is from a specific DataFrame column i.e. coast

import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt


IN: data['coast'].dtypes
OUT: 
CategoricalDtype(categories=[0, 1], ordered=False)


IN: data['coast'].value_counts()  
OUT: 
0    21450
1      163
Name: coast, dtype: int64

Shown below syntax is the defined function used, to get the bar chart.

def code(c):
    plt.rc('figure', figsize=(10, 5))
        
    ax = c.value_counts().plot(kind='bar')
    
    for value in ax:
        height = value.get_height()
        plt.text(value.get_x() + value.get_width()/2., 
                 1.002*height,'%d' % int(height), ha='center', va='bottom')
   

However, the bar chart does appears without the values on the bar which is shown below.

IN: code(data['coast'])
OUT:

enter image description here

But the below error message appears

---------------------------------------------------------------------------
TypeError: 'AxesSubplot' object is not iterable
---------------------------------------------------------------------------

How could I resolve the above error to get the below bar chart.

enter image description here

Advertisement

Answer

As @Henry Ecker commented, you should be iterating over ax.patches. The pandas plot function is returning the axis not the patches/rectangles.

enter image description here

df = pd.DataFrame({
    'coast': np.random.choice(['Cat1','Cat2'], size=20000, p=[0.9, 0.1])
})

def code(c):
    plt.rc('figure', figsize=(10, 5))
        
    ax = c.value_counts().plot(kind='bar')
    
    for value in ax.patches:
        height = value.get_height()
        plt.text(value.get_x() + value.get_width()/2., 
                 1.002*height,'%d' % int(height), ha='center', va='bottom')

code(df.coast)

Alternatively, just make the plot and get your own value counts. The X axis for bar charts is just an array 0 to number of bars (2 in this case).

enter image description here

df = pd.DataFrame({
    'coast': np.random.choice(['Cat1','Cat2'], size=20000, p=[0.9, 0.1])
})

def code(c):
    plt.rc('figure', figsize=(10, 5))
    counts = c.value_counts()    
    ax = counts.plot(kind='bar')

    for i in range(len(counts)):
        ax.text(
            x = i,
            y = counts[i] + 600,
            s = str(counts[i]),
            ha = 'center', fontsize = 14
        )
    ax.set_ylim(0,25000)

code(df.coast)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement