Matplotlib是Python中最著名的绘图库。这里就是用matplotlib.pyplot
来绘制论文实验部分所需的折线图。
画出来的折线图:
所涉及到的要素有:
- 一个figure包含两个子图,用
subplot
实现 - 图片直接生成展示或者保存成pdf格式,用
plt.show()
或者pdf.savefig()
- 折线图的画法,点、线形状、颜色,参考Matplotlib 点、线形状及颜色
- 图的标题,图的坐标轴刻度,x、y轴标签
- 图的标注,用
plt.legend()
具体代码如下:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
#下面两句代码防止中文显示成方块
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['figure.dpi'] = 300 #图片像素
plt.rcParams['figure.figsize'] = (12.0, 4.0)
x_bits = [12, 24, 32, 48]
def joint_early():
with PdfPages('joint_early.pdf') as pdf:
#cifar10-----------------------------------
plt.subplot(1,2, 1) #cifar部分画在子图1中
y_early_students=[[0.741551,0.76498,0.77793,0.77558],
[0.79482,0.818521,0.82154,0.827666],
[0.86727,0.89018,0.90012,0.900969],
[0.87354,0.8927,0.90919,0.905798]
]
y_ours_students=[[0.76229,0.79393,0.78994,0.80432],
[0.80788,0.82604,0.84254,0.83907],
[0.87004,0.89094,0.90188,0.9048],
[0.87955,0.89755,0.91043,0.91302]]
#开始绘制
colors=['red','orange','blue','green']
markers=['o','v','*','s']
labels_early=['student-1-early','student-2-early',
'student-3-early','student-4-early']
labels_ours=['student-1-ours','student-2-ours',
'student-3-ours','student-4-ours']
for i in range(4):
color=colors[i]
plt.plot(x_bits,y_early_students[i],color=color,
marker=markers[i],linestyle='--',label=labels_early[i])
plt.plot(x_bits,y_ours_students[i],color=color,
marker=markers[i],linestyle='-',label=labels_ours[i])
plt.xticks(x_bits) #横轴只有这四个刻度
# plt.ylim(0.65, 0.93) #y坐标范围
plt.title("CIFAR10")
plt.xlabel("Number of bits") # 作用为横坐标轴添加标签 fontsize=12
plt.ylabel("MAP") # 作用为纵坐标轴添加标签
#sun-----------------------------------
plt.subplot(1,2, 2)#sun部分画在子图1中
# 数据准备
y_early_students = [[0.75348, 0.8166, 0.82471, 0.82749],
[0.78058, 0.83077, 0.83574, 0.84841],
[0.8249, 0.86114, 0.8627, 0.87235],
[0.83924, 0.86368, 0.8674, 0.87599]
]
y_ours_students = [[0.76123, 0.81592, 0.82724, 0.84166],
[0.78617, 0.83835, 0.84371, 0.85208],
[0.82594, 0.86230, 0.86595, 0.87225],
[0.83931, 0.86902, 0.87141, 0.87521]]
# 开始绘制
colors = ['red', 'orange', 'blue', 'green']
markers = ['o', 'v', '*', 's']
labels_early = ['student-1-early', 'student-2-early',
'student-3-early', 'student-4-early']
labels_ours = ['student-1-ours', 'student-2-ours',
'student-3-ours', 'student-4-ours']
for i in range(4):
color = colors[i]
plt.plot(x_bits, y_early_students[i], color=color,
marker=markers[i], linestyle='--', label=labels_early[i])
plt.plot(x_bits, y_ours_students[i], color=color,
marker=markers[i], linestyle='-', label=labels_ours[i])
plt.xticks(x_bits) # 横轴只有这四个刻度
# plt.ylim(0.7, 0.9) #y坐标范围
plt.title("SUN")
plt.xlabel("Number of bits") # 作用为横坐标轴添加标签 fontsize=12
plt.ylabel("MAP") # 作用为纵坐标轴添加标签
plt.legend()
# plt.show()
pdf.savefig() # 如果要保存,就需要去掉plt.show(),因为plt.show()会把figure清除掉