그룹화 된 막대 차트를 플로팅하고 주석을 추가하는 방법
Aug 20 2020
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()
이 코드 모듈의 출력은 정말 엉망입니다. 그러나 내가 기대하는 것은 그림의 막대 차트처럼 보일 것입니다. 내 코드에서 어떤 점이 정확하지 않은지 말씀해 주시겠습니까?

답변
2 TrentonMcKinney Aug 20 2020 at 02:38
- 에서 주석 JohanC는 ,
w = 0.8 / 3
현재 코드 주어진 문제를 해결합니다. - 그러나 플롯 생성은 다음을 사용하여 더 쉽게 수행 할 수 있습니다. pandas.DataFrame.plot
import pandas as pd
import matplotlib.pyplot as plt
# given the following code to create the dataframe
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
# your colors
colors = ['#5cb85c', '#5bc0de', '#d9534f']
# plot with annotations is probably easier
p1 = df.plot.bar(color=colors, figsize=(20, 8), ylabel='Percentage', title="The percentage of the respondents' interest in the different data science Area")
p1.set_xticklabels(p1.get_xticklabels(), rotation=0)
for p in p1.patches:
p1.annotate(f'{p.get_height():0.2f}', (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 10), textcoords = 'offset points')
