数据框:
student_id sequencefirst jig rec fre mon
0 105012 12 J1 R1 F1 M2
1 105147 18 J1 R1 F2 M4
2 105198 4 J2 R3 F1 M4
3 105207 7 J2 R3 F3 M5
4 105258 6 J2 R3 F3 M5
做柱状图:
方法1:
df['rec'].value_counts().plot.bar()
‘rec’计数统计柱状图;
方法2:
dfg = df.groupby('rec', as_index=False).student_id.count().sort_values('rec', ascending=True) dfg.plot.bar('rec','student_id')
按student_id计数(也可换成sum即求和),并按‘rec’升序排列作图;
显示中文标题:
plt.rcParams['font.sans-serif']=['SimHei'] #显示中文标题 plt.title('R_S刻度表',fontsize=16)
添加标签及百分比:
plt.style.use('seaborn')
plt.rcParams['font.sans-serif']=['SimHei'] #显示中文标题
# df['rec'].value_counts().plot.bar()
print(df.columns)
dfg = df.groupby('rec', as_index=False).student_id.count().sort_values('rec', ascending=True)
dfg.plot.bar('rec','student_id',label='student_id计数')
x=0
Count=dfg['student_id'].sum()
for i in dfg['student_id']:
plt.text(x,i+50000,str('{:.2f}'.format(dfg['student_id'][x]/Count*100))+'%',ha='center') #添加百分比
plt.text(x,i+10000,str('{}'.format(i)+'人'),ha='center') #添加标签,位置、高度、内容、居中
x+=1
plt.title('R_S刻度表',fontsize=16)
plt.savefig('D:/yongqing-kang/example/NBD/clv04/R-s.png')
plt.show()
先groupby计数,然后sum(计数),做比例,i+10000是根据数据大小调整标签位置