Python-Matplotlib包的使用

本文详细介绍了Python的Matplotlib库,包括散点图、折线图、条形图、直方图、饼状图、箱型图的创建方法及参数解释,以及颜色和样式设置、子图、多图、网格、图例、坐标轴操作、注释、文字添加、Tex公式、区域填充和图形美化等高级功能。通过实例解析,帮助读者全面掌握Matplotlib的使用技巧。


Matplotlib 官方文件参考网址:https://matplotlib.org/index.html

一、散点图

1.语法

plt.scatter(x,y,s=100,c=‘r’,marker=’<’,alpha=‘0.5’)

2.参数解释

  • s:点的大小
  • c:点颜色
  • marker:点形状
  • alpha: 点的透明度

3.示例

x=np.random.randn(1000)
y1=np.random.randn((1000))
plt.scatter(x,y1,s=100,c='r',marker='<',alpha='0.5')
plt.show()

在这里插入图片描述

二、折线图

1.语法

plot(x,y,‘格式’)

2.参数解释

在这里插入图片描述

3.示例

#linspace为生成等区间的数值
x=np.linspace(-10,10,20)
y=x**2
plt.plot(x,y,color='green', linestyle='dashed', marker='<',
     markerfacecolor='blue', markersize=12)
plt.savefig('折线图')
plt.show()

在这里插入图片描述

三、条形图

1.语法

垂直方向:
plt.bar(x,height,color,edgecolor,width=0.8,bottom=None,align=‘center’)

水平方向:
plt.bar(x=0,height,color,edgecolor,width=0.8,bottom,align=‘center’,orientation=‘horizontal’)

2.参数解释

  • left:条图最左边的横坐标
  • color:条形图颜色。
  • edgecolor:条图边缘颜色。
  • width:条图宽度,可以相同,可以不同。
  • bottom :条图底部位置。
  • align:柱子的位置与x值的对应关系。center:条图位于x值的中心位置,edge:表示条图位于x值的边缘位置
  • orientation:horizontal代表绘制水平方向的条形图

3.示例

示例 1:普通条形图

N=5
y=[20,10,30,25,15]
index = np.arange(N)
p1 = plt.bar(x=index, height=y,width=0.5,bottom=100,color='red')
plt.savefig('条形图')
plt.show()

在这里插入图片描述
示例 2:并列条形图

index = np.arange(4)
sales_BJ=[52,55,63,53]
sales_SH=[44,66,55,41]

bar_width=0.3

plt.bar(index,sales_BJ,bar_width,color='b')
plt.bar(index+bar_width,sales_SH,bar_width,color='r')
plt.savefig('并列条形图')
plt.show()

在这里插入图片描述
示例3:堆积条形图

plt.bar(index,sales_BJ,bar_width,color='b')
plt.bar(index,sales_SH,bar_width,color='r',bottom=sales_BJ)
plt.savefig('层叠条形图')
plt.show()

在这里插入图片描述

四、直方图

1.语法

plt.hist(x,bins=10,color=‘red’,normed=True)

2.参数说明

  • x 表示要绘图的数据
  • bins 每个部分显示的标签
  • colors 指定直方图颜色
  • normed 是否对数据标准化

3.示例

示例 1:标准化直方图,返回 y 轴为x频率

mu = 100  # mean of distribution
sigma = 20  # standard deviation of distribution
x = mu + sigma * np.random.randn(2000)
plt.savefig('直方图')
plt.hist(x, bins=10,color='red',normed=True)

在这里插入图片描述
示例 2:非标准化直方图,返回 y 轴为 x 出现的次数;

plt.hist(x, bins=50,color='green',normed=False)
plt.savefig('非标准化直方图')
plt.show()

在这里插入图片描述

五、饼状图

1.语法

plt.pie(x,y,height,c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值