python - 'numpy.ndarray' object has no attribute 'barh' 是什么意思,如何纠正?

标签 python numpy matplotlib plot seaborn

我想绘制一个 5 x 4 的地 block 。相同的代码如下

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)

错误表明 'numpy.ndarray' 对象没有属性 'barh'。请帮忙。

下面发布了完整的错误。

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'

最佳答案

阅读以下两个问题及其答案会有所帮助:

在您的代码 fig, axis = plt.subplots(5, 4,figsize=[25,10]) 中,axis 是一个二维 numpy 数组。如果您使用单个索引对其进行索引,则会从中取出一行,而不是单个轴。

在不更改太多代码的情况下,最简单的解决方案是使用展平数组进行索引,

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

或者只是预先展平轴阵列,

fig, axis = plt.subplots(5, 4,figsize=[25,10])
axis = axis.flatten()
#  keep rest of code the same

关于python - 'numpy.ndarray' object has no attribute 'barh' 是什么意思,如何纠正?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45769005/

相关文章:

python - python方法属于对象还是类?

python - 为什么 db.insert(dict) 在使用 pymongo 时将 _id 键添加到 dict 对象

python - 仅在 numpy 中打印真正的根

python - Pandas 对所有行进行排序

python - Numpy 向量化算法找到第一个大于当前元素的 future 元素

python - 使用弯曲(路径跟踪)向量在 python 中进行流可视化

python - 键盘中断tensorflow运行并在此时保存

python - 如何在 Python 中仅对列表中的几个值进行排序

python - 将两个图表重叠绘制

python - pyplot step 函数不为第一个/最后一个点绘制水平