1. 程式人生 > >python matplotlib 雙Y軸 以及 曲線標誌位置

python matplotlib 雙Y軸 以及 曲線標誌位置

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1)  # 生成一個numpy陣列物件,0到5,間隔為0.1

y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, label='sin', color='red')
plt.legend(loc=3)  # 左上
# 'best'         : 0(自適應方式)
# 'upper right'  : 1
# 'upper left'   : 2
# 'lower left'   : 3
# 'lower right'  : 4
# 'right'        : 5
# 'center left'  : 6
# 'center right' : 7
# 'lower center' : 8
# 'upper center' : 9
# 'center'       : 10

plt.twinx()  # 新增一條Y軸,
plt.plot(x, y2, label='cos', color='blue')
plt.legend(loc='upper right')  # 右上

plt.show()