1

I want to plot a 5 x 4 plots. The code for the same is below

fig, axis = plt.subplots(5, 4,figsize=[25,10])
i = 0
for channel in np.unique(data_recent['channel_id']):
    for year in np.unique(data_recent['year']):
        filter_data = data_recent.loc[(data_recent['channel_id']==str(channel)) & (data_recent['year']==year)]
        topics_count = []
        for topic in list(sumbags.keys()):
            topics_count.append([topic, filter_data[str(topic)].sum()])
        topics_group = pd.DataFrame(topics_count, columns = ['topics','count'])
        topics_group = topics_group.sort_values(by='count', ascending=False)[:5]
        print (channel, year)
        print (topics_group)

        sns.barplot(x = 'count', y = 'topics', data = topics_group, ax = axis[i])
        axis[i].set_title("Top 5 topics for " + str(channel) + " " + str(year))
        axis[i].set_ylabel("Topics")
        axis[i].set_xlabel("Count")
        fig.subplots_adjust(hspace=0.4)    
        fig.subplots_adjust(wspace=0.4)
        i += 1

print (i)

The error says that 'numpy.ndarray' object has no attribute 'barh'. Please help.

The full error is posted below.

AttributeError                            Traceback (most recent call last)
<ipython-input-511-edab5430d06a> in <module>()
     12         print (topics_group)
     13 
---> 14         sns.barplot(x = 'count', y = 'topics', data = topics_group, ax = axis[i])
     15         axis[i].set_title("Top 5 topics for " + str(channel) + " " + str(year))
     16         axis[i].set_ylabel("Topics")

C:\Users\Sujoy\Anaconda3\lib\site-packages\seaborn\categorical.py in barplot(x, y, hue, data, order, hue_order, estimator, ci, n_boot, units, orient, color, palette, saturation, errcolor, errwidth, capsize, ax, **kwargs)
   2902         ax = plt.gca()
   2903 
-> 2904     plotter.plot(ax, kwargs)
   2905     return ax
   2906 

C:\Users\Sujoy\Anaconda3\lib\site-packages\seaborn\categorical.py in plot(self, ax, bar_kws)
   1593     def plot(self, ax, bar_kws):
   1594         """Make the plot."""
-> 1595         self.draw_bars(ax, bar_kws)
   1596         self.annotate_axes(ax)
   1597         if self.orient == "h":

C:\Users\Sujoy\Anaconda3\lib\site-packages\seaborn\categorical.py in draw_bars(self, ax, kws)
   1552         """Draw the bars onto `ax`."""
   1553         # Get the right matplotlib function depending on the orientation
-> 1554         barfunc = ax.bar if self.orient == "v" else ax.barh
   1555         barpos = np.arange(len(self.statistic))
   1556 

AttributeError: 'numpy.ndarray' object has no attribute 'barh'
Sujoy De
  • 229
  • 2
  • 3
  • 11
  • 1
    On which line does the error occur? – John Zwinck Aug 19 '17 at 08:00
  • Your title has little to nothing to do with your actual error. –  Aug 19 '17 at 08:00
  • There is no `barh` at all in your code: either your error appears elsewhere in your code, or it happens somewhere in the matplotlib code. Please show the full traceback. –  Aug 19 '17 at 08:01
  • I have pasted the full error – Sujoy De Aug 19 '17 at 08:03
  • Possible duplicate of [Axes from plt.subplots() is a "numpy.ndarray" object and has no attribute "plot"](https://stackoverflow.com/questions/37967786/axes-from-plt-subplots-is-a-numpy-ndarray-object-and-has-no-attribute-plot) – gereleth Aug 19 '17 at 09:10

2 Answers2

16

It would help to read the following two questions and their answers:

In your code fig, axis = plt.subplots(5, 4,figsize=[25,10]), axis is a 2D numpy array. If you index it with a single index, you take one row out of it, not a single axes.

Without changing too much of your code, the easiest solution is to use the flattened array to index,

sns.barplot(..., ax = axis.flatten()[i])
axis.flatten()[i].set_title(...)
#etc.

or just flatten the axis array beforehands,

fig, axis = plt.subplots(5, 4,figsize=[25,10])
axis = axis.flatten()
#  keep rest of code the same
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
1

You can also avoid the flatten() call using this approach:

sns.barplot(x = 'count', y = 'topics', data = topics_group, ax = axis[i,j])

where axis[i,j] the indexes of your subplots matrix.

Alex Granovsky
  • 2,996
  • 1
  • 15
  • 10