matplotlib范围曲线简例

想在画(平均)loss 曲线时顺便表示方差,即每一个 epoch 的平均 loss 用 plot 画曲线,而在曲线周围用一个浅色区域表示方差。效果:
matplotlib范围曲线简例_第1张图片

参考 [1-3],用到 matplotlib.pyplot.fill_between 函数。为显示对浅色区及其边界的样式控制,这里用了花里胡哨的配色。

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

# 造两个 loss
loss1, loss2 = [], []
for epoch in range(1, 20):
    loss1.append(1 / epoch + np.random.randn(100) * 0.1)
    loss2.append(math.exp(-epoch) + np.random.randn(100) * 0.1)

# 纵轴:loss 均值、方差
loss1 = np.asarray(loss1)
mu1 = np.mean(loss1, axis=1)
sigma1 = np.std(loss1, axis=1)

loss2 = np.asarray(loss2)
mu2 = np.mean(loss2, axis=1)
sigma2 = np.std(loss2, axis=1)

# 横轴:epoch
epochs = list(range(loss1.shape[0]))


fig = plt.figure()
# 均值:用 plot 画
plt.plot(epochs, mu1, label="loss1", linewidth=2, marker='s', c='r') # 红
plt.plot(epochs, mu2, label="loss2", linewidth=2, marker='+', c='b') # 蓝

# 方差:浅色区,用 fill_between
plt.fill_between(
    epochs,         # x
    mu1 + sigma1,   # y upper
    mu1 - sigma1,   # y lower
    color='g',      # 绿,color = edgecolor + facecolor
    linewidth=2,    # 浅色区边界粗细
    alpha=0.2       # 浅色区能见度
)
plt.fill_between(
    epochs,
    mu2 + sigma2,
    mu2 - sigma2,
    edgecolor='none',   # 不要边界
    facecolor='orange', # 橙
    linewidth=2,
    alpha=0.2
)

plt.title("loss curve")
plt.xticks(epochs, list(map(str, epochs)))		# 设横轴标
plt.xlabel("epoch")
plt.ylabel("loss")
plt.legend(fancybox=True, framealpha=0)			# 透明图例
fig.savefig("loss-curve.png", transparent=True)	# 透明背景

References

  1. Filling range of graph in matplotlib
  2. 使用matplotlib绘制范围波动曲线图
  3. python绘制浅色范围曲线
  4. How to export plots from matplotlib with transparent background?
  5. Transparent, fancy legends

你可能感兴趣的:(环境,matplotlib,python,fill_between,范围曲线)