机器学习和数据分析-matplotlib绘制柱状图和饼状图

文章目录

柱状图

1.启动jupyter notebook
2.创建一个新的notebook,并导入matplotlib

import matplotlib.pyplot as plt

在这里插入图片描述
3.绘制柱状图

x = ['A',"B","C","D"] #表示4个季度
y = [10,30,20,60] #表示4个对应的销量
plt.bar(x,y)
plt.show()

在这里插入图片描述
4.指定颜色:color ,指定条形宽度:width , 增加网格:plt.grid(True)

plt.bar(x,y,color='g',width=0.3)
plt.grid(True)
plt.show()

在这里插入图片描述
5.在柱状图上面写上数字,使用plt.text()函数,比如plt.text(0.1,20,‘test’)

plt.bar(x,y,color='g',width=0.3)
plt.grid(True)
plt.text(0.1,20,'test')
plt.show()

在这里插入图片描述
6.获取柱状图的每根柱子,并拿到每个柱子的高度,代码如下:

rect = plt.bar(x,y,color='g',width=0.3)
for ind,item in enumerate(rect):
    _x = item.get_x()
    _y = item.get_height()
    plt.text(_x,_y,y[ind])
plt.grid(True)
plt.show()

在这里插入图片描述
7.为了使数字和柱子没那么紧凑,可以在x轴和y轴上面加上一定偏移量,并且增加y轴的范围,代码如下:

rect = plt.bar(x,y,color='g',width=0.3)
for ind,item in enumerate(rect):
    _x = item.get_x()+0.1 #0.1为偏移量
    _y = item.get_height()+1  #1为偏移量
    plt.text(_x,_y,y[ind])
plt.ylim(0,70) #设置y轴的范围
plt.grid(True)
plt.show()

在这里插入图片描述

饼状图

1.绘制一个简单的饼状图,只需要传入一个y值

y = [10,30,20,60]
plt.pie(y)
plt.show()

在这里插入图片描述
2.在每块扇形上面加上含义,传入label = x

x = ['A','B','C','D']
y = [10,30,20,60]
plt.pie(y,labels=x)
plt.show()

在这里插入图片描述
3.在饼状图上面加上百分比,autopct=’%.2f%%’,将默认椭圆改成正圆

plt.axes(aspect=1) #正圆
plt.pie(y,labels=x,autopct='%.2f%%')
plt.show()

在这里插入图片描述
4.突出第一部分,explode = [0.1,0,0,0], 边上加上阴影: shadow=True

plt.axes(aspect=1) #正圆
plt.pie(y,labels=x,autopct='%.2f%%',explode=[0.1,0,0,0],shadow=True)
plt.show()

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值