Matplotlib绘制柱形图

前言

       柱形图,又称长条图,柱状图、条状图、条形图等,是一种以长方形的长度为变量的统计图表。柱形图用来比较两个或以上的数据(不同时间或者不同条件),只有一个变量,通常利用于较小的数据集分析。Matplotlib绘制柱形图时主要使用bar函数,语法如下:

plt.bar(x, height, width, align='center')

x:x轴数据;    height:柱子的高度,也就是y轴的数据;    width:浮点型,柱子的宽度,默认值为0.8,可以指定固定值;    align:对齐方式,如center(居中)和edge(边缘),默认值为center。

一、基本柱形图

       绘制2017年至2023年图书销售额分析图,代码如下:

import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码
x=['2017年', '2018年', '2019年', '2020年', '2021年', '2022年', '2023年']
height=[120045, 305678, 485100, 505088, 984511, 1885556, 2288775]
plt.grid(axis="y", which="major")  # 生成虚线网格
#x、y轴标签
plt.xlabel('年份')
plt.ylabel('线上销售额(元)')
#图表标题
plt.title('2013-2019年线上图书销售额分析图')
plt.bar(x,height,width = 0.5,align='center',color = 'b',alpha=0.5,bottom=0.8)
#设置每个柱子的文本标签,format(b,',')格式化销售额为千位分隔符格式
for a,b in zip(x,height):
    plt.text(a, b,format(b,','), ha='center', va= 'bottom',fontsize=9,color = 'b',alpha=0.9)
#图例
plt.legend(['销售额'])
plt.show()

       结果如图所示: 

二、多柱形图

       绘制个平台的图书销售额分析图,代码如下:

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel('books.xlsx',sheet_name='Sheet2')
plt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码
x=df['年份']    # [2013, 2014, 2015, 2016, 2017, 2018, 2019]
y1=df['京东']    # [6800, 89044, 156010, 157856, 558909, 1298890, 1525004]
y2=df['天猫']    # [32550, 187800, 234708, 290017, 321400, 432578, 584500]
y3=df['自营']    # [80695, 28834, 94382, 57215, 104202, 154088, 179271]

width =0.25  #柱子宽度,若显示n个柱子,则width值需小于1/n ,否则柱子会出现重叠
#y轴标签
plt.ylabel('线上销售额(元)')
#图表标题
plt.title('2017-2023年线上图书销售额分析图')
plt.bar(x,y1,width = width,color = 'darkorange')
plt.bar(x+width,y2,width = width,color = 'deepskyblue')
plt.bar(x+2*width,y3,width = width,color = 'g')
#设置每个柱子的文本标签,format(b,',')格式化销售额为千位分隔符格式
for a,b in zip(x,y1):
    plt.text(a, b,format(b,','), ha='center', va= 'bottom',fontsize=8)
for a,b in zip(x,y2):
    plt.text(a+width, b,format(b,','), ha='center', va= 'bottom',fontsize=8)
for a, b in zip(x, y3):
    plt.text(a + 2*width, b, format(b, ','), ha='center', va='bottom', fontsize=8)
plt.legend(['京东','天猫','自营'])#图例
plt.show()

 运行程序,得到下图:

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值