import matplotlib.pyplot as plt import numpy as np # 基礎用法 x = np.linspace(-1,1,100) y = 2*x + 1 plt.plot(x,y) plt.show()
figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True)dom
num:圖像編號或名稱,數字爲編號 ,字符串爲名稱
figsize:指定figure的寬和高,單位爲英寸;
dpi:指定繪圖對象的分辨率,即每英寸多少個像素,缺省值爲80;
facecolor:背景顏色;
edgecolor:邊框顏色;
frameon:是否顯示邊框;spa
x = np.linspace(-1,1,100) y1 = 2*x + 1 y2 = x**2 plt.figure() plt.plot(x,y1) plt.figure() plt.plot(x,y2) plt.show()
#設置座標軸 x = np.linspace(-3,3,100) y1 = 2*x + 1 y2 = x**2 # xy範圍 plt.xlim(-1,2) plt.ylim(-2,3) # xy軸描述 plt.xlabel('I am X') plt.ylabel('I am Y') # 設置xy軸單位長度 new_ticks = np.linspace(-1,2,10) plt.xticks(new_ticks) plt.yticks([-1,0,1,2,3], ['l1','l2','l3','l4','l5']) # 獲取座標軸,設置邊框 ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') # 設置座標軸刻度位置 ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # 設置邊框零點 ax.spines['bottom'].set_position(('data',0)) ax.spines['left'].set_position(('data',0)) plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--') plt.plot(x,y2,color='blue',linewidth=2.0,linestyle='-') plt.show()
#legend 圖例 x = np.linspace(-3,3,100) y1 = 2*x + 1 y2 = x**2 # 保存圖線 l1, = plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--') l2, = plt.plot(x,y2,color='blue',linewidth=2.0,linestyle='-') plt.legend(handles=[l1,l2],labels=['test1','test2'],loc='best') plt.show()
x = np.linspace(-3,3,100) y1 = 2*x + 1 y2 = x**2 # 獲取座標軸,設置邊框 ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') # 設置邊框零點 ax.spines['bottom'].set_position(('data',0)) ax.spines['left'].set_position(('data',0)) # 圖像標註 x0 = 0.5 y0 = 2*x0 + 1 # 畫點 plt.scatter(x0,y0,s=50,color='green') # 畫虛線 從(x0,y0)到(x0,0)點畫一條虛線 plt.plot([x0,x0],[y0,0],'k--') plt.plot([x0,0],[y0,y0],'k--') # 畫一條指向箭頭 plt.annotate(r'$2x+1=%s$' % y0, xy=(x0,y0), xytext=(-10,+50), textcoords='offset points',fontsize=14, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) # 設置顯示漢字 plt.rcParams['font.sans-serif']=['SimHei'] plt.text(-2.3,6,u'你好',fontdict={'size':'14','color':'green'}) plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--') plt.plot(x,y2,color='blue',linewidth=2.0,linestyle='-') plt.show()
# 散點圖 x = np.arange(5) y = np.arange(5) plt.scatter(x,y) plt.show() plt.xlim((-3,2)) plt.ylim((-3,2)) plt.xticks(()) plt.yticks(()) plt.scatter(np.random.normal(0,1,500), np.random.normal(0,1,500), s=50,c='y',alpha=0.5) plt.show()
# 直方圖 x = np.arange(10) y = 2**x+1 plt.bar(x,y) for x,y in zip(x,y): plt.text(x,y,'%s'%y,ha='center',va='bottom') plt.show()
# subplot子圖 plt.figure() plt.subplot(2,2,1) plt.plot([1,4],[-3,4]) plt.subplot(2,2,2) plt.plot([1,4],[-3,4]) plt.subplot(2,2,3) plt.plot([1,4],[-3,4]) plt.subplot(2,2,4) plt.plot([1,4],[-3,4]) plt.show()