Matplotlib基础

Matplotlib基础

一、本课目标
  • 了解matplotlib的应用
  • 掌握pyplot绘制线图
  • 掌握pyplot绘制散点图
  • 掌握pyplot绘制条形图
  • 掌握pyplot绘制直方图
  • 掌握pyplot绘制饼图
二、Matplotlib介绍
  • Matplotlib 是 Python 的绘图库,它能让使用者很轻松地将数据图形化,并且提供多样化的输出格式
  • Matplotlib 可以绘制线图、散点图、条形图、柱状图、饼图、3D 图形、甚至是图形动画等等
三、Matplotlib 应用
  • Matplotlib 通常与 NumPy 和 SciPy(Scientific Python)一起使用, 这种组合广泛用于替代 MatLab,是一个强大的科学计算环境,有助于我们通过 Python 学习数据科学或者机器学习。
  • SciPy 是一个开源的 Python 算法库和数学工具包。
  • SciPy 包含的模块有最优化、线性代数、积分、插值、特殊函数、快速傅里叶变换、信号处理和图像处理、常微分方程求解和其他科学与工程中常用的计算
四、Matplotlib 安装
  • 安装 matplotlib 库:
    • pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
  • 安装完成后,我们就可以通过 import 来导入 matplotlib 库:
    • import matplotlib
    • print(matplotlib. _version_)
五、Pyplot
  • Pyplot 是 Matplotlib 的子库,提供了绘图 API
  • Pyplot 是常用的绘图模块,能很方便让用户绘制 2D 图表
  • Pyplot 包含一系列绘图函数的相关函数,每个函数会对当前的图像进行一些修改
  • 使用 import 导入 pyplot 库,并设置一个别名 plt:
    • import matplotlib.pyplot as plt
六、Pyplot 常用函数
  • plot():用于绘制线图和散点图
  • scatter():用于绘制散点图
  • bar():用于绘制垂直条形图和水平条形图
  • hist():用于绘制直方图
  • pie():用于绘制饼图
  • show():用于绘制图像
  • subplots():用于创建子图
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 100])
plt.plot(xpoints, ypoints)
plt.show()

在这里插入图片描述

七、plot()方法
  • 用于绘制点和线,语法格式如下:
    • 画单条线:plot([x], y, [fmt], *, data=None, **kwargs)
    • 画多条线:plot([x], y, [fmt], [x2], y2, [fmt2], …, **kwargs)
  • 参数说明:
    • x, y:点或线的节点,x 为 x 轴数据,y 为 y 轴数据,数据可以列表或数组。
    • fmt:可选,定义基本格式(如颜色、标记和线条样式)。
    • **kwargs:可选,用在二维平面图上,设置指定属性,如标签,线的宽度等。
    • 常用颜色字符:‘b’ 蓝色,‘m’ 洋红色,‘g’ 绿色,‘y’ 黄色,‘r’ 红色,‘k’ 黑色,‘w’ 白色,‘c’ 青绿色。多条曲线不指定颜色时,会自动选择不同颜色。
  • 常用线型参数:‘‐’ 实线,‘:’ 虚线。
  • 常用标记字符:‘.’ 点标记,‘,’ 像素标记(极小点),‘o’ 实心圈标记
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints, 'o')
plt.show()

在这里插入图片描述

xpoints = np.array([1, 2, 6, 8])
ypoints = np.array([3, 8, 1, 10])
plt.plot(xpoints, ypoints)
plt.show()

在这里插入图片描述

ypoints = np.array([3, 10])
plt.plot(ypoints)
plt.show()

在这里插入图片描述

ypoints = np.array([3, 8, 1, 10, 5, 7])
plt.plot(ypoints)
plt.show()

在这里插入图片描述

x = np.arange(0, 4*np.pi, 0.01)
y = np.sin(x)
z = np.cos(x)
plt.plot(x, y, "r", x, z, "y")
plt.show() 

在这里插入图片描述

八、散点图
  • 使用 pyplot 中的 scatter() 方法来绘制散点图
# 散点图
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = np.array([1, 4, 9, 16, 7, 11, 23, 18])
# plt.scatter(x, y)
plt.plot(x, y, "*")
plt.show()

在这里插入图片描述

x =[]
y = []
for i in range(100):
    x.append(np.random.randint(0,100))
    y.append(np.random.randint(0,100))
    if i == 0:
        print(x[0], y[0])
    if i == 99:
        print(x[99], y[99])

plt.scatter(x, y) 
plt.plot(x, y)
plt.show()

在这里插入图片描述

九、柱状图
  • pyplot 中的 bar() 方法来绘制柱形图
x = np.array(["Season-1", "Season-2", "Season-3", "Season-4"])
y = np.array([12, 22, 6, 18])
plt.bar(x, y, width = 0.3)
plt.show()

在这里插入图片描述

df.plot(rot = 45, kind = "barh",title = "shai")
df.plot(rot = 0, kind = "bar",title = "shai")
plt.show()

在这里插入图片描述

在这里插入图片描述

names = ['tom','jack', 'rose']
chinese = [90, 80, 70]
math = [85, 90, 75]
df = pd.DataFrame({"chinese": chinese, "math": math}, names)
print(df)
df.plot(kind = "bar", rot = 0, title = "mark", xlabel="names", ylabel="score" )
plt.show()

在这里插入图片描述

十、饼图
  • 使用 pyplot 中的 pie() 方法来绘制饼图
percent = [25, 35, 25, 15]
plt.title("Area")
plt.pie(percent)
plt.legend(["A", "B", "C", "D"])
plt.show()

在这里插入图片描述

十一、直方图
  • 使用 pyplot 中的 hist() 方法来绘制直方图
data = np.random.randn(10000)
plt.hist(data, bins = 30, color = 'skyblue')
zhfont = matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf")
# plt.title("中文显示 - 测试", fontproperties=zhfont)
plt.rcParams["font.sans-serif"] = ["SimHei"] 
plt.title('柱状图')
plt.xlabel('value')
plt.ylabel('Frequency')
%config InlineBackend.figure_format='svg'
plt.show()

在这里插入图片描述

十二、子图
x = np.arange(0, 10, 0.5)
y = np.sin(x)
z = np.cos(x)
# 绘制两行一列的子图
ax1 = plt.subplot(2, 1, 1)
ax2 = plt.subplot(2, 1, 2)
# g 表示线条的颜色为绿色(green)
# o 表示点的形状为圆形
# -. 表示线的风格为点划线
ax1.plot(x, y, 'go-.')
ax2.plot(x, z, 'go-.')
ax1.grid()
ax2.grid()
ax1.set_title('sin(x)')
ax2.set_title('cos(x)')
plt.show()

在这里插入图片描述

production = [1125, 1725, 2250, 2875, 2900, 3750, 4125]
temp = [6, 8, 10, 13, 14, 16, 21]
ax2 = plt.subplot(2, 2, 3)
ax2.scatter(temp, production)

在这里插入图片描述

plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
labels = ['果汁', '矿泉水', '绿茶', '其他', '碳酸饮料']
num = [6, 10, 11, 8, 15]
exploade = [0, 0.2, 0, 0, 0]
ax3 = plt.subplot(2, 2, 4)
# num:一个数值列表,表示饼图各个扇区的大小。
# labels:与num列表中数值对应的标签列表,用于标识饼图的每个扇区。
# autopct:一个字符串,定义了扇区内部百分比文本的格式。在这个例子中,'%.2f%%' 表示百分比将以两位小数显示,例如 12.34%。
# shadow:一个布尔值,如果设置为 True,则饼图的扇区将显示阴影效果。
# startangle:一个数值,表示饼图起始位置的角度,以度为单位。在这个例子中,140 表示饼图从140度的角度开始绘制
ax3.pie(num, labels=labels, autopct='%.2f%%', shadow=True, startangle=140, explode=exploade)
# 设置为矢量图格式
%config InlineBackend.figure_format='svg'
plt.show()

在这里插入图片描述

十三、中文显示-1
  • Matplotlib 中文显示不是特别友好,默认情况下,中文部分不能正常显示,可以通过以下两个方法:
    • 设置 Matplotlib 的字体参数
    • 下载使用支持中文的字体库
  • 字体参数
    • plt.rcParams[‘font.family’] = 'SimHei
十四、中文显示-2
  • 使用字体库
    • 官网:https://source.typekit.com/source-han-serif/cn/
    • GitHub 地址:https://github.com/adobe-fonts/source-hansans/tree/release/OTF/SimplifiedChinese
  • 将字体文件放在当前执行的代码目录中
    • #fname 为 你下载的字体库路径,注意 SourceHanSansSC-Bold.otf 字体的路径
    • zhfont = matplotlib.font_manager.FontProperties(fname=“SourceHanSansSCBold.otf”)
    • plt.title(“中文显示 - 测试”, fontproperties=zhfont)
data = np.random.randn(1000)
plt.hist(data, bins = 30, color = 'skyblue')
zhfont = matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf")
plt.title("中文显示 - 测试", fontproperties=zhfont)
#plt.rcParams["font.sans-serif"] = ["SimHei"] 
# plt.title('DATA hist(Test)')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()

在这里插入图片描述

十五、总结
  • 了解matplotlib的应用
  • 掌握pyplot绘制线图
  • 掌握pyplot绘制散点图
  • 掌握pyplot绘制条形图
  • 掌握pyplot绘制直方图
  • 掌握pyplot绘制饼图
  • 14
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

AI小白日记

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

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

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

打赏作者

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

抵扣说明:

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

余额充值