如何绘制和注释分组条形图 [英] How to plot and annotate a grouped bar chart

查看:99
本文介绍了如何绘制和注释分组条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个关于 Python 中 matplotlib 的棘手问题.我想创建一个包含多个代码的分组条形图,但图表出错了.你能给我一些建议吗?代码如下.

将 numpy 导入为 np将熊猫作为pd导入文件="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DV0101EN/labs/coursera/Topic_Survey_Assignment.csv"df = pd.read_csv(file,index_col = 0)df.sort_values(by = ['非常感兴趣'],轴= 0,升序= False,inplace = True)df['很感兴趣']=df['很感兴趣']/2233df['有点感兴趣']=df['有点感兴趣']/2233df ['不感兴趣'] = df ['不感兴趣']/2233dfdf_chart=df.round(2)df_chart标签=['数据分析/统计','机器学习','数据可视化',大数据(Spark/Hadoop)"、深度学习"、数据新闻"]very_interested = df_chart ['非常感兴趣']有点感兴趣=df_chart['有点感兴趣']not_interested = df_chart ['不感兴趣']x=np.arange(len(标签))w=0.8fig,ax = plt.subplots(figsize =(20,8))rects1 = ax.bar(x-w,非常感兴趣,w,label ='非常感兴趣',color ='#5cb85c')rects2=ax.bar(x,somewhat_interested,w,label='有点感兴趣',color='#5bc0de')rects3=ax.bar(x+w,not_interested,w,label='不感兴趣',color='#d9534f')ax.set_ylabel('百分比',fontsize=14)ax.set_title(受访者对不同数据科学领域的兴趣百分比",字体大小=16)ax.set_xticks(x)ax.set_xticklabels(标签)ax.legend(字体大小=14)def autolabel(rects):文本"在* rects *中的每个条上方附加一个文本标签,以显示其高度.对于 rect 中的 rect:高度= rect.get_height()ax.annotate('{}'.format(height),xy=(rect.get_x() + rect.get_width()/3, 高度),xytext = {0,3),#3点垂直偏移textcoords =偏移点",ha ='center',va ='bottom')自动标签(rects1)自动标签(rects2)自动标签(rects3)fig.tight_layout()plt.show()

这个代码模块的输出真的是一团糟.但是我期望的应该看起来像图片中的条形图.您能告诉我代码中哪一点不正确吗?

解决方案

导入和DataFrame

 将熊猫作为pd导入导入matplotlib.pyplot作为plt#给出以下代码来创建数据框文件="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DV0101EN/labs/coursera/Topic_Survey_Assignment.csv"df = pd.read_csv(file,index_col = 0)df.sort_values(by = ['非常感兴趣'],轴= 0,升序= False,inplace = True)df['很感兴趣']=df['很感兴趣']/2233df ['有兴趣的人'] = df ['有兴趣的人']/2233df['不感兴趣']=df['不感兴趣']/2233

使用自 matplotlib v3.4.2

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆