【问题标题】:Bar chart plotting issue: TypeError: 'AxesSubplot' object is not iterable条形图绘图问题:TypeError:'AxesSubplot' 对象不可迭代
【发布时间】:2021-09-20 14:43:50
【问题描述】:

下面显示的是条形图的分类数据详细信息,它来自特定的DataFrame 列,即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

下面的语法是用来获取条形图的定义函数。

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')
   

但是,条形图确实会出现,但条形图上没有显示如下所示的值。

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

但出现以下错误信息

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

如何解决上述错误以获得下面的条形图。

【问题讨论】:

  • ax 包含绘图,而不是数据。看看here 来注释条形图。
  • 这能回答你的问题吗? Annotate bars with values on Pandas bar plots
  • @Henry Ecker: 或者可能超过value_counts
  • for value in ax.patches: 将按预期运行,无需进一步修改。但是复制中的任何选项都有效。
  • 我不清楚这个问题或上一个问题中的问题,因为我的答案与your first question 上的任何一个答案都没有不同。我的答案将与 tdy's 几乎相同,谁经历了如何使用 countplotcatplot

标签: python pandas numpy matplotlib seaborn


【解决方案1】:

正如@Henry Ecker 评论的那样,您应该迭代 ax.patches。 pandas plot 函数返回的是轴而不是补丁/矩形。

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)

或者,只需制作情节并获得您自己的价值。条形图的 X 轴只是一个数组,从 0 到条数(在本例中为 2)。

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-20
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2020-10-13
    相关资源
    最近更新 更多