1. 程式人生 > >用python和matplotlib畫雙座標系曲線

用python和matplotlib畫雙座標系曲線

 有時候寫論文的時候不免會遇到畫曲線圖,而且還有可能需要畫雙座標系(雙Y軸)的曲線圖,在百度中找了許久,先mark一下,以下程式碼就是我論文中用到的,以後應該還會用到,先儲存在這裡。結果圖如下:

import matplotlib.pyplot as plt
import numpy as np
import scipy.io as sio

x = np.arange(0., 1000, 2, dtype=np.int32)
xx = np.arange(0., 2000, 4, dtype=np.int32)
data = sio.loadmat('C://Users//gmt//Desktop//bn.mat')
y1 = data["loss"][:1000, 0]
y2 = data["testacc"][:1000, 0]
data = sio.loadmat('C://Users//gmt//Desktop//wobn.mat')
y11 = data["loss"][:1000, 0]
y22 = data["testacc"][:1000, 0]

fig = plt.figure()

ax1 = fig.add_subplot(111)
ax1.plot(xx, y1[x], color='red', label='Loss with BN')
ax1.plot(xx, y11[x], color='green', label='Loss without BN')
ax1.set_ylabel('Cross Entropy Loss')
ax1.set_xlabel('Iterations')
ax1.set_ylim(0, 1500)
ax1.set_xlim(0, 1000)
plt.legend(loc='lower left')


ax2 = ax1.twinx()
ax2.plot(xx, y2[x], color='blue', label='Test Accuracy with BN')
ax2.plot(xx, y22[x], color='skyblue', label='Test Accuracy without BN')
ax2.set_ylabel('Testset Accuracy')
ax2.set_xlabel('Iterations')
ax2.set_ylim(0, 1)
ax2.set_xlim(0, 1000)
plt.legend(loc='upper right')
plt.show()