畫直線圖dom
import matplotlib.pyplot as plt plt.plot([1,2,3]) plt.ylabel('some numbers') plt.show()
基本畫圖ide
1 import numpy as np 2 import matplotlib.pyplot as plt 3 from pylab import * 4 5 # 定義數據部分 6 x = np.arange(0., 10, 0.2) 7 y1 = np.cos(x) 8 y2 = np.sin(x) 9 y3 = np.sqrt(x) 10 11 # 繪製 3 條函數曲線 12 plt.plot(x, y1, color='blue', linewidth=1.5, linestyle='-', marker='.', label=r'$y = cos{x}$') 13 plt.plot(x, y2, color='green', linewidth=1.5, linestyle='-', marker='*', label=r'$y = sin{x}$') 14 plt.plot(x, y3, color='m', linewidth=1.5, linestyle='-', marker='x', label=r'$y = \sqrt{x}$') 15 16 # 座標軸上移 17 ax = plt.subplot(111) 18 ax.spines['right'].set_color('none') # 去掉右邊的邊框線 19 ax.spines['top'].set_color('none') # 去掉上邊的邊框線 20 21 # 移動下邊邊框線,至關於移動 X 軸 22 ax.xaxis.set_ticks_position('bottom') 23 ax.spines['bottom'].set_position(('data', 0)) 24 25 # 移動左邊邊框線,至關於移動 y 軸 26 ax.yaxis.set_ticks_position('left') 27 ax.spines['left'].set_position(('data', 0)) 28 29 # 設置 x, y 軸的取值範圍 30 plt.xlim(x.min()*1.1, x.max()*1.1) 31 plt.ylim(-1.5, 4.0) 32 33 # 設置 x, y 軸的刻度值 34 plt.xticks([2, 4, 6, 8, 10], [r'2', r'4', r'6', r'8', r'10']) 35 plt.yticks([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], 36 [r'-1.0', r'0.0', r'1.0', r'2.0', r'3.0', r'4.0']) 37 38 # 添加文字 39 plt.text(4, 1.68, r'$x \in [0.0, \ 10.0]$', color='k', fontsize=15) 40 plt.text(4, 1.38, r'$y \in [-1.0, \ 4.0]$', color='k', fontsize=15) 41 42 # 特殊點添加註解 43 plt.scatter([8,],[np.sqrt(8),], 50, color ='m') # 使用散點圖放大當前點 44 plt.annotate(r'$2\sqrt{2}$', xy=(8, np.sqrt(8)), xytext=(8.5, 2.2), fontsize=16, color='#090909', arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=0.1', color='#090909')) 45 46 # 設置標題、x軸、y軸 47 plt.title(r'$the \ function \ figure \ of \ cos(), \ sin() \ and \ sqrt()$', fontsize=19) 48 plt.xlabel(r'$the \ input \ value \ of \ x$', fontsize=18, labelpad=88.8) 49 plt.ylabel(r'$y = f(x)$', fontsize=18, labelpad=12.5) 50 51 # 設置圖例及位置 52 plt.legend(loc='upper left') 53 # plt.legend(['cos(x)', 'sin(x)', 'sqrt(x)'], loc='up right') 54 55 # 顯示網格線 56 plt.grid(True) 57 58 # 顯示繪圖 59 plt.show() 60 #保存 61 #plt.savefig()
經常使用圖形函數
曲線圖:spa
x=np.arange(-5,5,0.1) y=x ** 2 plt.plot(x,y) plt.show()
灰度圖code
import matplotlib.pyplot as plt import numpy as np x=np.random.normal(size=1000) plt.hist(x,bins=10) plt.show()
散點圖:orm
import matplotlib.pyplot as plt import numpy as np x=np.random.normal(size=1000) y=np.random.normal(size=1000) plt.scatter(x,y) plt.show()
箱式圖:blog
import matplotlib.pyplot as plt import numpy as np x=np.random.normal(size=1000) plt.boxplot(x) plt.show()