Below shown is the categorical data detail for the bar chart, which is from a specific DataFrame
column i.e. coast
JavaScript
x
16
16
1
import seaborn as sns
2
import matplotlib as mpl
3
import matplotlib.pyplot as plt
4
5
6
IN: data['coast'].dtypes
7
OUT:
8
CategoricalDtype(categories=[0, 1], ordered=False)
9
10
11
IN: data['coast'].value_counts()
12
OUT:
13
0 21450
14
1 163
15
Name: coast, dtype: int64
16
Shown below syntax is the defined function used, to get the bar chart.
JavaScript
1
11
11
1
def code(c):
2
plt.rc('figure', figsize=(10, 5))
3
4
ax = c.value_counts().plot(kind='bar')
5
6
for value in ax:
7
height = value.get_height()
8
plt.text(value.get_x() + value.get_width()/2.,
9
1.002*height,'%d' % int(height), ha='center', va='bottom')
10
11
However, the bar chart does appears without the values on the bar which is shown below.
JavaScript
1
3
1
IN: code(data['coast'])
2
OUT:
3
But the below error message appears
JavaScript
1
4
1
---------------------------------------------------------------------------
2
TypeError: 'AxesSubplot' object is not iterable
3
---------------------------------------------------------------------------
4
How could I resolve the above error to get the below bar chart.
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.
JavaScript
1
16
16
1
df = pd.DataFrame({
2
'coast': np.random.choice(['Cat1','Cat2'], size=20000, p=[0.9, 0.1])
3
})
4
5
def code(c):
6
plt.rc('figure', figsize=(10, 5))
7
8
ax = c.value_counts().plot(kind='bar')
9
10
for value in ax.patches:
11
height = value.get_height()
12
plt.text(value.get_x() + value.get_width()/2.,
13
1.002*height,'%d' % int(height), ha='center', va='bottom')
14
15
code(df.coast)
16
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).
JavaScript
1
20
20
1
df = pd.DataFrame({
2
'coast': np.random.choice(['Cat1','Cat2'], size=20000, p=[0.9, 0.1])
3
})
4
5
def code(c):
6
plt.rc('figure', figsize=(10, 5))
7
counts = c.value_counts()
8
ax = counts.plot(kind='bar')
9
10
for i in range(len(counts)):
11
ax.text(
12
x = i,
13
y = counts[i] + 600,
14
s = str(counts[i]),
15
ha = 'center', fontsize = 14
16
)
17
ax.set_ylim(0,25000)
18
19
code(df.coast)
20