使用matplotlib绘制范围波动曲线
??论文在做数据分析时,经常需要绘制曲线图,例如对不同的超参数对应的实验性能变化。由于实际实验需要重复执行多次并获取均值和波动范围,需要同时在曲线图中展示。本文介绍并提供使用基于matplotlib绘制简单精美的曲线图。
??展示预期效果,例如给出两个方法在不同训练样本数量条件下的准确率变化情况:
图像特点:
- 可对比多个不同的方法,不同方法的使用不同颜色、类型的曲线进行绘制;
- 可展示每个方法对应的极差波动范围,以展示不同方法的稳定程度;
- 横坐标部分为2倍指数递增;
对应代码:
import numpy as np
import sys
import sklearn
from sklearn import metrics
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot as plt
plt.figure(figsize=(6, 5))
plt.title("Dataset", size = 24)
models = ['Baseline', 'Our Proposal']
cnt = 0
maker = ['^','s']
x = [16, 32, 64, 128, 256, 512]
x_names = ['16', '32', '64', '128', '256', '512']
results = {
'Baseline': [81.42, 88.19, 90.94, 92.55, 93.58, 94.27],
'Our Proposal': [93.46, 92.55, 92.67, 94.50, 95.07, 95.18]
}
ranges_top = {
'Baseline': [85.32, 89.65, 91.66, 92.89, 93.92, 94.61],
'Our Proposal': [93.98, 93.46, 93.00, 94.84, 95.30, 95.30]
}
ranges_bottom = {
'Baseline': [76.26, 86.50, 90.13, 92.20, 93.35, 94.04],
'Our Proposal': [92.89, 91.98, 92.32, 94.21, 94.95, 95.07]
}
for model_name in models:
y = np.array(results[model_name]).astype(np.float)
y1 = np.array(ranges_top[model_name]).astype(np.float)
y2 = np.array(ranges_bottom[model_name]).astype(np.float)
makevery =1
plt.xscale("log", base=2)
plt.plot(x, y, label=model_name, linewidth=2, marker=maker[cnt], markevery=makevery, markersize=6)
plt.fill_between(x, y1, y2,
alpha=0.3
)
plt.xlabel("#Training (K)",fontsize=18)
plt.ylabel("Accuracy (%)",fontsize=18)
plt.ylim([70.0, 100.0])
plt.xticks(x, x_names, rotation=0, size = 20)
plt.yticks(np.arange(70, 100, 5), rotation=0, size = 20)
cnt+=1
font1 = {
'weight' : 'normal',
'size' : 22,
}
plt.legend(loc = "lower right", prop=font1)
plt.grid(False)
ax=plt.gca()
ax.spines['right'].set_color('#ccc')
ax.spines['top'].set_color('#ccc')
ax.spines['left'].set_color('#ccc')
ax.spines['bottom'].set_color('#ccc')
ax.spines['right'].set_linewidth('2.0')
ax.spines['top'].set_linewidth('2.0')
ax.spines['left'].set_linewidth('2.0')
ax.spines['bottom'].set_linewidth('2.0')
plt.savefig("./"+'show.png', dpi=120, bbox_inches='tight')
|