【问题标题】:How can write text inside bars of a bar plot?如何在条形图的条内写入文本?
【发布时间】:2021-07-31 01:32:34
【问题描述】:

我需要帮助打印每个栏内“投诉类型”列中的名称。
下面的代码用X=BoroughY=Count绘制条形图
请帮助我,因为涉及三列。

df1 = dict({'Borough':['BROOKLYN','QUEENS','MANHATTAN','BRONX','STATEN ISLAND','Unspecified'],
           'Complaint Type':['Blocked Driveway','Blocked Driveway','Noise - Street/Sidewalk','Blocked 
            Driveway','Illegal Parking','Illegal Parking'], 
           'Count':[28148,31644,20550,12755,4886,1040]})
df2=pd.DataFrame(df1)
df2

输出:

    **Borough         Complaint Type              Count**
0   BROOKLYN          Blocked Driveway            28148
1   QUEENS            Blocked Driveway            31644
2   MANHATTAN         Noise - Street/Sidewalk     20550
3   BRONX             Blocked Driveway            12755
4   STATEN ISLAND     Illegal Parking             4886
5   Unspecified       Illegal Parking             1040

对于条形图:

df2.plot(x ="Borough",y="Count",kind='bar',alpha=0.6,color='red',figsize=(7,7),title='Most frequent complaint type in each Borough')
plt.xlabel('Borough')
plt.ylabel('Count')

【问题讨论】:

    标签: python matplotlib plot data-visualization bar-chart


    【解决方案1】:

    您可以使用plt.annotate 显示“投诉类型”。

    df2.plot(x ="Borough",y="Count",kind='bar',alpha=0.6,color='red',figsize=(7,7),
             title='Most frequent complaint type in each Borough')
    plt.xlabel('Borough')
    plt.ylabel('Count')
    
    for i in range(0, len(df2['Borough'])):
        plt.annotate(str(df2['Complaint Type'][i]), xy=(i, (df2['Count'][i] / 2)), 
        ha='center', va='center', weight='bold', size=10)
    


    也看看这个帖子。
    Adding value labels on a matplotlib bar chart

    【讨论】:

      猜你喜欢
      • 2021-06-24
      • 2017-03-22
      • 2021-08-21
      • 2017-07-25
      • 2017-11-13
      • 1970-01-01
      相关资源
      最近更新 更多