matplotlib.pyplot常见用法查询

Anarkenker Posted on 10 days ago 29 Views


matplotlib.pyplot Python 中一个常用的绘图库 matplotlib 子模块,它提供了一个类似 MATLAB 的绘图接口,用于快速生成各种图表。通常来说是与 numpy 结合使用, 现在让我们来介绍一下关于这个库,首先调用这个库。

import matplotlib.pyplot as plt
import numpy as np

一般来说我们都是以一下这个步骤进行画图的, 现在是一个正弦图像的演示

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-2 * np.pi , 2 * np.pi, 1000)
y = np.sin(x)
plt.figure()
plt.plot(x, y, label='sin(x)', color='blue')
plt.title('Sine Wave')
plt.xlabel('x (radians)')
plt.ylabel('sin(x)')
plt.legend()
plt.grid(True)
plt.show()

先解释一下这个numpy库中函数的用法

x = np.linspace(a, b, c)

这个是在a, b区间分成c段, c越大则生成的图形就越平滑, 然后介绍一下这个plt库的常见函数

一、基础用法

plt.figure()
plt.figure(figsize=(宽, 高), dpi=分辨率, facecolor=背景色, edgecolor=边框色)

用于 创建一个新的图像窗口(figure对象)

参数名 类型 说明(中文) 说明(英文)
num int 或 str 图像编号或名称(可选) Figure number or name (optional)
figsize tuple 图像大小(宽度, 高度),单位是英寸 Figure size in inches (width, height)
dpi int 分辨率(每英寸多少像素),默认100 Dots per inch, default is 100
facecolor str 图像背景色,如 'white'、'#eeeeee' Background color of the figure
edgecolor str 边框颜色 Edge color of the figure
tightlayout bool 是否自动调整布局以防止内容重叠 Whether to use tight layout automatically
使用例子
import matplotlib.pyplot as plt

plt.figure(facecolor='#eeeeee')  # 设置图像背景为浅灰色
plt.plot([0, 1, 2], [0, 1, 4])
plt.title("gray")
plt.show()

补充严肃对应的十六进制

颜色名 代码 颜色效果
白色 ffffff 完全白
黑色 000000 完全黑
红色 ff0000 纯红
绿色 00ff00 纯绿
蓝色 0000ff 纯蓝
灰色 888888 中灰
浅灰色 eeeeee 接近白
这个在ide里应该可以手动调, 反正在我的ide可以调颜色的
plt.plot()
plt.plot(x, y, color='blue', linestyle='-', marker='o', label='数据名')

plt.scatter()
plt.scatter(x, y, color='red', marker='x', s=大小, label='样本')

plt.bar()
plt.bar(x, height, width=0.8, color='blue', label='标签')

plt.pie()
plt.pie(data, labels=标签列表, autopct=显示百分比, colors=颜色列表, startangle=起始角度, explode=突出效果)

plt.plot()

参数 说明
x,y 一组 xy 数据
color 线的颜色(如 red, 00ff00
linestyle 线型(如 实线, 虚线)
marker 每个点的形状(如 o 圆点, x 叉号)
label 用于图例

plt.scatter()

参数 说明
x,y 点的位置
color 点的颜色
marker 点的形状(如 ox、'^' 等)
s 点的大小(默认是 20
label 图例名称

plt.bar()

plt.barh() 用于画横向柱状图

参数 含义
x 每个柱子的横坐标(可以是数字或分类名)
height 每个柱子的高度
width 柱子的宽度,默认 0.8
color 柱子的颜色
label 用于图例说明

plt.pie()

参数名 说明(中文) 说明(英文)
data 各部分的数值 Values for each wedge
labels 每一块的标签列表 Labels for each slice
autopct 是否显示百分比,如 %.1f% Show percentage on the chart
colors 各扇区的颜色列表 (可选) List of colors for each wedge
startangle 起始角度(以 x 轴为 0°,逆时针旋转) Start angle of the pie chart
explode 是否突出某一块,传入列表,如 [0,0.1,0,0] 这是突出第二块饼状图,explode = [0.1,0,0.1,0] 这是突出第一和第三块善行<br> Pull out a slice for emphasis
plt.title('Sine Wave')
plt.xlabel('x (radians)')
plt.ylabel('sin(x)')
plt.legend()
plt.grid(True)
plt.show()

前面四个都是给图片贴一个是 label 前三个都是为了打上注释, 第四个是为每条线做一个图标, 表明每条线所对应的信息的一般来说是位于这个图的右上角。倒数第二个是让图形画出一个灰线背景的表格图,最后一个是让图形展现出来。
至此, 这是单个图形的图的常见画法已经完全讲解完成, 下面则是稍微进阶一些的用法

二、多图形以及面向对象的用法

plt.subplot()
plt.subplot(nrows, ncols, index)
'''
`nrows`:行数(多少行子图)
`ncols`:列数(多少列子图)
`index`:当前子图的位置(从 1 开始,从左到右、从上到下数)
'''

在这里是多图形画图的方法,这并非是面向对象风格的。在结尾我们通常要 plt.tight_layout() 这个是避免子图重叠的函数, 有了这个函数我们才能保证我们的子图变的有序。在每一个子图上面我们都需要引用一下 plt.subplot() 这个函数, 但是我们只需要变更的是这个 index 这一个参数。

下面我们来介绍一下面向对象(OO风格)的用法介绍。对比面向函数式接口的库的风格, 面对对象风格的写法明显更加清晰, 在日常使用中我们更加推荐面向对象风格的写法使用。一般来说我们写面向对象风格的代码的时候遵循以下步骤

import matplotlib.pyplot as plt

# 创建画布和子图
fig, ax = plt.subplots()

# 用 ax 对象调用方法
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title("Title")
ax.set_xlabel("X axis")
ax.set_ylabel("Y axis")

plt.show()

fig,ax=plt.subplots() 中的 fig 是创建一个全局的画布。然后 ax 是坐标轴的区域, 也就是你实际作画的区域。

fig, (ax1, ax2) = plt.subplots(1, 2)  # 一行两个子图

这样就完成了面向对象风格的代码的书写, 那么在这种代码中我们该如何调用, 下面有个表格可供参考

功能 函数式接口 面向对象接口
画图 plt.plot() ax.plot()
设置标题 plt.title() ax.set-title()
设置 X/Y 标签 plt.xlabel() ax.set_xlabel()
加图例 legend plt.legend() ax.legend()
设置 x 坐标范围 plt.xlim() ax.set_xlim()
设置 y 坐标范围 plt.ylim() ax.set_ylim()

其他的用法相同。至此这个库的基础用法我们已经介绍完毕。如果我们想要画出一些函数的图像譬如说 sin(x) 。我们可以借助 numpy 库, 这里就不一一讲解了。

This author has not provided a description.
Last updated on 2025-07-16