plt.bar图表

数据框: 

  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是根据数据大小调整标签位置

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用Python中的pandas库进行数据可视化时,我们可以使用plot.bar函数来绘制柱状图,并通过指定参数来添加图例。 要添加图例,我们可以在使用plot.bar函数时,将参数legend设置为True,这样就会自动在图表中添加垂直的图例。例如: ``` import pandas as pd # 创建一个DataFrame data = {'城市': ['北京', '上海', '广州', '深圳'], '销售额': [500, 800, 700, 600]} df = pd.DataFrame(data) # 绘制柱状图并添加图例 ax = df.plot.bar(x='城市', y='销售额', legend=True) # 显示图表 plt.show() ``` 执行以上代码,就会生成一个柱状图,并在图表的右上角添加一个垂直的图例,图例的内容是根据DataFrame中的数据自动生成的。 如果想要进一步自定义图例的位置和样式,我们可以使用pandas提供的图例相关的函数。例如,我们可以使用legend函数来修改图例的位置、标题以及是否显示边框等。以下是一个示例: ``` import pandas as pd # 创建一个DataFrame data = {'城市': ['北京', '上海', '广州', '深圳'], '销售额': [500, 800, 700, 600]} df = pd.DataFrame(data) # 绘制柱状图并添加图例 ax = df.plot.bar(x='城市', y='销售额') # 自定义图例的位置和样式 ax.legend(loc='upper right', title='城市销售额', frameon=False) # 显示图表 plt.show() ``` 在这个示例中,我们使用了legend函数来修改图例的位置为右上角,修改图例的标题为"城市销售额",并且关闭了图例的边框。 总之,使用Python的pandas库中的plot.bar函数,我们可以在柱状图中添加图例,通过设置相关参数来控制图例的样式和位置。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值