最近用Python绘图时,需要绘制光滑的曲线。本文随机生成50个[0,1]的随机数用来绘制光滑的曲线,实现效果如下:

python loss 曲线 平滑 python plot 光滑曲线_python

代码如下:

import numpy as np
import random
import matplotlib.pyplot as plt
from scipy.interpolate import make_interp_spline
plt.rcParams['font.family'] = ['Times New Roman']
# plt.rcParams['font.sans-serif'] = ['SimHei']
#
plt.rcParams['xtick.direction'] = 'in'  # 将x周的刻度线方向设置向内
plt.rcParams['ytick.direction'] = 'in'  # 将y轴的刻度方向设置向内
# 生成50个随机数作为y值
data = [random.random() for _ in range(50)]
# 生成x值
x = np.arange(len(data))


x_new = np.linspace(0, len(data)-1, 300)
spl = make_interp_spline(np.arange(len(data)), data, k=3)
y_new = spl(x_new)

# 绘制曲线
plt.plot(x_new, y_new, ms=4, label=u'curve', color="blue")

plt.ylim(0,1)
plt.xlim(-5,55)
plt.margins(0)

# 添加标题和标签
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
# 显示图表
plt.show()