【Python】Matplotlib(学习笔记)

一、Matplotlib概述

1、什么是Matplotlib

画二维图表的python库

2、Matplotlib图像结构

3、Matplotlib三层结构

容器层 => 画板层Canvas、画布层Figure、绘图区/坐标系(x、y轴张成的区域)

辅助显示层

图像层

二、基础绘图功能

1、模块导入

matplotlib.pyplot包含了一系列类似于matlab的画图函数,它的函数作用于当前图形(tiqure)的当前坐标系(axes)

import matplotlib.pyplot as plt

2、折线图绘制

plt.figure()
plt.plot([1,2,3,4,5,6,7],[17,17,18,19,20,12,17])
plt.show()

3、设置画布属性

figsize : 画布长宽

dpi : 图像的清晰度

plt.figure(figsize=(1080,720), dpi=300)

4、保存图像

需要写在plt.show()之前

plt.savefig("./img/demo.png")

5、添加自定义x、y刻度

plt.xticks(x, **kwargs)
plt.yticks(y, **kwargs)

6、添加网格显示

plt.grid(True, linestyle="--", alpha=0.5)

7、添加描述信息

plt.xlabel("时间")
plt.ylabel("温度")
plt.title("标题")

8、多个曲线的绘制

多次调用plt.plot()函数

9、图例的显示

在plot中添加label标签

plt.figure()
plt.plot([1,2,3,4,5,6,7],[17,17,18,19,20,12,17],label="shanghai")
plt.plot([1,2,3,4,5,6,7],[10,5,2,8,10,10,8],label="beijing")
# 显示图例
plt.legend()
plt.show()

10、多个坐标系显示

面向对象的画图方法

figure, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 8), dpi=80)
axes[0].plot([1,2,3,4,5,6,7],[17,17,18,19,20,12,17])
axes[1].plot([1,2,3,4,5,6,7],[10,5,2,8,10,10,8])
plt.show()

三、常见图标

1、应用场景

折线图(plot):某事物、某指标随时间的变化状况

散点图(scatter):关系/规律

柱状图(bar):统计/对比

直方图(histogram):分布状况

饼图(pie π):占比

2、散点图绘制

x = [12.3,15.3,12.5,15.5,9.6,19.8,12.9]
y = [10,5,2,8,10,10,8]

plt.figure(figsize=(25, 8), dpi=80)
plt.scatter(x,y)
plt.show()

3、柱状图绘制

name = ["a", "b", "c"]
value = [988, 698, 789]

plt.figure(figsize=(10, 8), dpi=80)
plt.bar(range(len(name)), value)
plt.xticks(range(len(name)), name)
plt.show();

4、直方图绘制

组数:在统计数据时,我们把数据按照不同的范围分成几个组,分成的组的个数称为组数

组距:每一组两个端点的差

value = [155, 153, 168, 162, 158, 152, 160, 164, 170, 161, 158, 172, 163,
       166, 176, 140, 162, 172, 168, 148, 141, 140, 176, 172, 141, 164,
       140, 167, 164, 159, 143, 174, 159, 178, 157, 157, 149, 152, 163,
       170, 175, 168, 171, 155, 169, 152, 178, 154, 162, 175, 160, 152,
       167, 164, 150, 152, 147, 174, 142, 179, 174, 142, 153, 170, 177,
       169, 163, 177, 165, 151, 165, 175, 140, 140, 176, 147, 155, 152,
       174, 177, 158, 174, 144, 157]

plt.figure(figsize=(10, 8), dpi=80)
plt.hist(value, bins=10)
plt.show()

直方图与柱状图的对比:

  1. 直方图展示数据的分布,柱状图比较数据的大小。
  2. 直方图X轴为定量数据,柱状图X轴为分类数据。
  3. 直方图柱子无间隔,柱状图柱子有间隔宽度可不一,柱状图柱子宽度须一致

直方图注意:组距的设置、考虑y轴的变量

5、饼图的绘制

value = [155, 53, 198, 62]
plt.figure(figsize=(10, 8), dpi=80)
plt.pie(value, autopct="%1.2f%%")
plt.axis("equal")
plt.show()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wmh1024

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值