我遇到了一个关于Python中matplotlib的棘手问题。我想创建一个有几个代码的分组条形图,但图表出错了。你能给我提些建议吗?代码如下。
import numpy as np
import pandas as pd
file="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=['Very interested'], axis=0,ascending=False,inplace=True)
df['Very interested']=df['Very interested']/2233
df['Somewhat interested']=df['Somewhat interested']/2233
df['Not interested']=df['Not interested']/2233
df
df_chart=df.round(2)
df_chart
labels=['Data Analysis/Statistics','Machine Learning','Data Visualization',
'Big Data (Spark/Hadoop)','Deep Learning','Data Journalism']
very_interested=df_chart['Very interested']
somewhat_interested=df_chart['Somewhat interested']
not_interested=df_chart['Not interested']
x=np.arange(len(labels))
w=0.8
fig,ax=plt.subplots(figsize=(20,8))
rects1=ax.bar(x-w,very_interested,w,label='Very interested',color='#5cb85c')
rects2=ax.bar(x,somewhat_interested,w,label='Somewhat interested',color='#5bc0de')
rects3=ax.bar(x+w,not_interested,w,label='Not interested',color='#d9534f')
ax.set_ylabel('Percentage',fontsize=14)
ax.set_title("The percentage of the respondents' interest in the different data science Area",
fontsize=16)
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend(fontsize=14)
def autolabel(rects):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 3, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
fig.tight_layout()
plt.show()
这个代码模块的输出真是一团糟。但我所期望的应该看起来像图片中的条形图。你能告诉我我的代码中哪一点不正确吗?
1条答案
按热度按时间xiozqbni1#
导入和DataFrame
使用since
matplotlib v3.4.2
matplotlib.pyplot.bar_label
和pandas.DataFrame.plot
fmt
参数完成,但更复杂的格式化应该使用labels
参数完成,如How to add multiple annotations to a barplot所示。.bar_label
的其他详细信息和示例,请参见How to add value labels on a bar chart在
matplotlib v3.4.2
之前使用w = 0.8 / 3
将解决这个问题,给定当前代码。pandas.DataFrame.plot
可以更轻松地生成绘图