Search code examples
pythonnumpyplotseabornattributeerror

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


I wrote this code, but it gives me an AttributeError saying that the plot doesn't have bar. How can I fix it?

import seaborn as sns

fig, (ax1) = plt.subplots(ncols=2, figsize=(25, 7.5), dpi=100)
fig.suptitle(f'Counts of Observation Labels in ciciot_2023 ', fontsize=25)
sns.countplot(x="class_label", palette="OrRd_r", data=dataset, order=dataset['class_label'].value_counts().index, ax=ax1)

ax1.set_title('ciciot2023', fontsize=20)
ax1.set_xlabel('label', fontsize=15)
ax1.set_ylabel('count', fontsize=15)
ax1.tick_params(labelrotation=90)

plt.show()
AttributeError                            Traceback (most recent call last)
<ipython-input-19-685308b57f2d> in <cell line: 4>()
      2 fig, (ax1) = plt.subplots(ncols=2, figsize=(25, 7.5), dpi=100)
      3 fig.suptitle(f'Counts of Observation Labels in ciciot_2023 ', fontsize=25)
----> 4 sns.countplot(x="class_label", palette="OrRd_r",  data=dataset,  order=dataset['class_label'].value_counts().index, ax=ax1)
      5 
      6 ax1.set_title('ciciot2023', fontsize=20)

/usr/local/lib/python3.10/dist-packages/seaborn/categorical.py in draw_bars(self, ax, kws)
   1543         """Draw the bars onto `ax`."""
   1544         # Get the right matplotlib function depending on the orientation
-> 1545         barfunc = ax.bar if self.orient == "v" else ax.barh
   1546         barpos = np.arange(len(self.statistic))
   1547 

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

Solution

  • In fig,(ax1)= plt.subplots(ncols=2, figsize=(25, 7.5), dpi=100), ax1 is an array of axes (since you created two columns). Perhaps you tried to unpack it, by using the (ax1) syntax, but that does nothing here: these are just parentheses around a variable name.

    Instead, try

    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(25, 7.5), dpi=100)
    

    to get your two axes.