使用 Matplotlib 绘制函数曲线的编码范式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from __future__ import annotations

import matplotlib.pyplot as plt
import numpy as np

# ==================== 1. 数据生成 ====================
# 生成 x 轴数据(示例:从 0 到 2π,均匀取 200 个点)
x = np.linspace(0 , 2 * np.pi , 200)

# 生成多个 y 函数(可根据需要添加/修改)
# 同时定义每个函数曲线的绘图风格
y_functions = {
    "sin(x)":     {
        'data': np.sin(x) ,
        'style':{ 'color':'blue' , 'linestyle':'-' , 'linewidth':1 } ,
        } ,
    "cos(x)":     {
        'data': np.cos(x) ,
        'style':{ 'color':'red' , 'linestyle':'-' , 'linewidth':2 } ,
        } ,
    "0.5*sin(2x)":{
        'data': 0.5 * np.sin(2 * x) ,
        'style':{ 'color':'green' , 'linestyle':':' , 'linewidth':3 , 'alpha':0.7 } ,
        } ,
    "exp(-x)":    {
        'data': np.exp(-x) ,
        'style':{ 'color':'purple' , 'linestyle':'-.' , 'linewidth':4 , 'marker':'o' } ,
        } ,
    }

# ==================== 2. 创建画布和坐标系 ====================
# 参数说明:
# fig-size: (宽, 高) 英寸
# dpi: 分辨率
fig , ax = plt.subplots(figsize = (10 , 6) , dpi = 100)

# ==================== 3. 绘制多条曲线 ====================
# 循环绘制所有曲线
for curve_func in y_functions:
    label = curve_func
    y = y_functions[ curve_func ][ 'data' ]
    style = y_functions[ curve_func ][ 'style' ]
    ax.plot(x , y ,
            label = label ,  # 图例标签
            **style ,  # 解包样式字典
            )

# ==================== 4. 添加图表元素 ====================
ax.legend(loc = 'upper right')  # 显示图例
ax.set_title("Multiple Function Curves" , fontsize = 14 , pad = 20)  # 标题
ax.set_xlabel("x-axis" , fontsize = 12)  # x轴标签
ax.set_ylabel("y-axis" , fontsize = 12)  # y轴标签

# ==================== 5. 自定义样式 ====================
ax.grid(True , linestyle = '--' , alpha = 0.6)  # 显示网格线
ax.set_xlim(0 , 2 * np.pi)  # 设置x轴范围
ax.set_ylim(-1.2 , 1.5)  # 设置y轴范围
ax.tick_params(axis = 'both' , labelsize = 10)  # 刻度标签大小

# ==================== 6. 显示/保存 ====================
plt.tight_layout()  # 自动调整子图间距
plt.show()

Clipboard_Screenshot_1766748085

中文显示乱码问题的处理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from __future__ import annotations

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

# 设置支持中文的字体
# font_name = 'Microsoft YaHei'
font_name = 'Kai'
matplotlib.rcParams['font.family'] = font_name
matplotlib.rcParams['font.size'] = 14
matplotlib.rcParams['axes.unicode_minus'] = False  # 正确显示负号

fig, ax = plt.subplots()  # 创建一个figure
x = np.linspace(0, 2, 100)
ax.plot(x, x, label = 'linear 线性')  # 绘制图像
ax.plot(x, x ** 2, label = 'quadratic 平方')
ax.plot(x, x ** 3, label = 'cubic 立方')
ax.set_xlabel('x 坐标轴')
ax.set_ylabel('y 坐标轴')
ax.set_title(f'Plot 示例-字体为 {font_name}')
ax.legend()

plt.show()  # 显示图像

image-20251226192259604