python 绘制并列条形图并添加数据标签

28 篇文章 2 订阅

利用python绘制并列的条形图。
(1)处理数据,计算每个区间的个数:
在这里插入图片描述

(2)plt.bar函数绘制条形图:

df = pd.read_excel('path of file ',sheet_name='Sheet1')

area_class = df['name']

lake_num = df['lake_number']

TP_lake_num = df['TP_2020_lake_number']

bar_width = 0.3  

index_lake = np.arange(len(area_class))

index_TP = index_lake + bar_width

plt.bar(index_lake, height=lake_num, width=bar_width, color='b', label='study_2020_lake')

plt.bar(index_TP, height=TP_lake_num, width=bar_width, color='g', label='TP_2020_lake')

plt.legend() 

plt.xticks(index_lake + bar_width/2, area_class)  

plt.ylabel('Number') 

plt.xlabel('Area (km$^{2}$)') 

plt.show()

显示结果:
在这里插入图片描述
(3)图形优化
为每个柱添加数据标签:

df = pd.read_excel('path of file',sheet_name='Sheet1')

fig, ax = plt.subplots()

area_class = df['name']

lake_num = df['lake_number']

TP_lake_num = df['TP_2020_lake_number']

bar_width = 0.3  

index_lake = np.arange(len(area_class))

index_TP = index_lake + bar_width

plt.bar(index_lake, height=lake_num, width=bar_width, color='b', label='study_lake')

for x, y in enumerate(df['lake_number'].values):
    
    # plt.text(x, y+1,y,ha='center', va='bottom')
    
    plt.text(x+0.1, y+1,y,ha='right',va='bottom')
    
plt.bar(index_TP, height=TP_lake_num, width=bar_width, color='g', label='TP_lake')

for a, b in enumerate(df['TP_2020_lake_number'].values):
    
    plt.text(a+0.1, b+1,b,ha='left',va='bottom')
    
plt.legend() 

plt.xticks(index_lake + bar_width/2, area_class)  

plt.ylabel('Number') 

plt.xlabel('Area (km$^{2}$)') 

plt.show()

显示结果:
在这里插入图片描述
plt.text()函数参数说明:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.text.html

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值