1. 程式人生 > >matplotlib 設定座標軸位置(spines),設定座標別名(xticks,yticks)

matplotlib 設定座標軸位置(spines),設定座標別名(xticks,yticks)

參考的這


import numpy as np
import matplotlib.pyplot as plt


plt.rcParams['font.sans-serif']='SimHei'
plt.figure(figsize=(8,5), dpi=80)
plt.subplot(111)

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C = np.cos(X)
S = np.sin(X)

plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
  [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
'''確定座標範圍 plt.axis([xmin, xmax, ymin, ymax]) axis()命令給定了座標範圍。 xlim(xmin, xmax)和ylim(ymin, ymax)來調整x,y座標範圍 ''' plt.ylim(C.min() * 1.1, C.max() * 1.1) plt.yticks([-1, 0, +1], [r'bottom', r'normal', r'top']) plt.annotate('local max',xy=(0,1),xytext=(1.2,1.2), arrowprops=dict(facecolor='red',shrink=0.04))
plt.xlabel('X軸',fontsize=12,color='red',rotation=60,verticalalignment='top') plt.ylabel('y軸',fontsize=14,color='blue',rotation=30,horizontalalignment='center') plt.text(-2,0.5,r'數學sin函式',rotation=30) plt.savefig('spine.png') # plt.show()