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()
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。