需求
在记笔记的时候,经常要画一些函数图来分析函数的特点。这里我们选择matplotlib作为绘图工具
首先导入matplotlib和numpy
import matplotlib.pyplot as plt
import numpy as np
绘制单个函数图像
以绝对值函数为例,python内置了绝对值函数abs()
x = np.arange(-10, 10, 0.1) # x轴采样
y = abs(x) # 计算对应的 y
plt.title('y=|x|') # 图像名称
plt.xlabel('x') # x轴标签
plt.ylabel('y') # y轴标签
plt.plot(x, y) # 绘制图像
plt.show() # 显示图像

绘制自定义函数图像
以 为例
首先自定义函数:
def fun(x):
return [k * k * k for k in x]
然后绘制图像,注意在matplotlib中也是可以使用Latex公式的
x = np.arange(-10, 10, 0.1)
y = fun(x)
plt.title(r'$y=x^3$') # 图像名称,使用Latex公式
plt.xlabel('x')
plt.ylabel('y')
plt.plot(x, y)
plt.show()

指定线条颜色
x = np.arange(-10, 10, 0.1)
y = fun(x)
plt.title(r'$y=x^3$') # 图像名称,使用Latex公式
plt.xlabel('x')
plt.ylabel('y')
plt.plot(x, y, 'r')
plt.show()

在同一个图片中绘制多种函数图像并标注
以 MAE, MSE, 和 Smooth L 损失函数为例
定义 Smooth L 损失
def sm1(x, beta=1):
return [0.5 * i * i / beta if abs(i) < beta else abs(i) - 0.5 * beta for i in x]
绘制包含三种函数的图像
x = np.arange(-2, 2, 0.1)
y1 = abs(x)
y2 = x * x
y3 = sm1(x)
plt.xlabel(r'$\hat{y}^{(i)} - y^{(i)}$')
plt.ylabel('Error')
plt.plot(x, y1, color='r', label='MAE')
plt.plot(x, y2, color='g', label='MSE')
plt.plot(x, y3, color='b', label='Smooth L')
plt.legend() # 标注
plt.show()
