numpy和matploptlib

numpypython

Numpy介紹

編輯編程

一個用python實現的科學計算,包括:一、一個強大的N維數組對象Array;二、比較成熟的(廣播)函數庫;三、用於整合C/C++和Fortran代碼的工具包;四、實用的線性代數、傅里葉變換和隨機數生成函數。numpy和稀疏矩陣運算包scipy配合使用更加方便。
NumPy(Numeric Python)提供了許多高級的數值編程工具,如:矩陣數據類型、矢量處理,以及精密的運算庫。

數據類型ndarray

編輯
NumPy provides an N-dimensional array type, the ndarray, which describes a collection of 「items」 of the same type.
NumPy提供了一個 N維數組類型ndarray,它描述了 相同類型的「items」的集合。
ndarray到底跟原生python列表的區別:
從圖中咱們能夠看出ndarray在存儲數據的時候,數據與數據的地址都是連續的,這樣就給使得批量操做數組元素時速度更快。
這是由於ndarray中的全部元素的類型都是相同的,而Python列表中的元素類型是任意的,因此ndarray在存儲元素時內存能夠連續,而python原生list就只能經過尋址方式找到下一個元素,這雖然也致使了在通用性能方面Numpy的ndarray不及Python原生list,但在科學計算中,Numpy的ndarray就能夠省掉不少循環語句,代碼使用方面比Python原生list簡單的多。
numpy內置了並行運算功能,當系統有多個核心時,作某種計算時,numpy會自動作並行計算
Numpy底層使用C語言編寫,內部解除了GIL(全局解釋器鎖),其對數組的操做速度不受Python解釋器的限制,效率遠高於純Python代碼。
ndarray的屬性

   生成數組的方法:
empty(shape[, dtype, order])
empty_like(a[, dtype, order, subok])
eye(N[, M, k, dtype, order])
identity(n[, dtype])
ones (shape[, dtype, order])
ones_like(a[, dtype, order, subok])
zeros (shape[, dtype, order])
zeros_like(a[, dtype, order, subok])
full(shape, fill_value[, dtype, order])
full_like(a, fill_value[, dtype, order, subok])

Matplotlib

編輯 討論
Matplotlib 是一個 Python 的 2D繪圖庫,它以各類硬拷貝格式和跨平臺的交互式環境生成出版質量級別的圖形。
 
中文名
繪圖庫
外文名
Matplotlib
所屬領域
計算機
做    用
繪圖
元    素
x軸和y軸
Matplotlib 是一個 Python 的 2D繪圖庫,它以各類硬拷貝格式和跨平臺的交互式環境生成出版質量級別的圖形 [1]   。
經過 Matplotlib,開發者能夠僅須要幾行代碼,即可以生成繪圖,直方圖,功率譜,條形圖,錯誤圖,散點圖等。
Matplotlib基礎知識
1.Matplotlib中的基本圖表包括的元素
x軸和y軸
水平和垂直的軸線
x軸和y軸刻度
刻度標示座標軸的分隔,包括最小刻度和最大刻度
x軸和y軸刻度標籤
表示特定座標軸的值
繪圖區域
實際繪圖的區域
2.hold屬性
hold屬性默認爲True,容許在一幅圖中繪製多個曲線;將hold屬性修改成False,每個plot都會覆蓋前面的plot。
可是目前不推薦去動hold這個屬性,這種作法(會有警告)。所以使用默認設置便可。
3.網格線
grid方法
使用grid方法爲圖添加網格線
設置grid參數(參數與plot函數相同)
.lw表明linewidth,線的粗細
.alpha表示線的明暗程度
4.axis方法
若是axis方法沒有任何參數,則返回當前座標軸的上下限
5.xlim方法和ylim方法
除了plt.axis方法,還能夠經過xlim,ylim方法設置座標軸範圍
6.legend方法
兩種傳參方法:
【推薦使用】在plot函數中增長label參數
在legend方法中傳入字符串列表
配置matplotlib參數
永久配置
matplotlib配置信息是從配置文件讀取的。在配置文件中能夠爲matplotlib的幾乎全部屬性指定永久有效的默認值
安裝級配置文件(Per installation configuration file)
Python的site-packages目錄下(site-packages/matplotlib/mpl-data/matplotlibrc)
系統級配置,每次從新安裝matplotlib後,配置文件會被覆蓋
若是但願保持持久有效的配置,最好選擇在用戶級配置文件中進行設置
對本配置文件的最佳應用方式,是將其做爲默認配置模板
用戶級.matplotlib/matplotlibrc文件(Per user .matplotlib/matplotlibrc)
用戶的Documents and Settings目錄
能夠用matplotlib.get_configdir()命令來找到當前用戶的配置文件目錄
當前工做目錄
代碼運行的目錄
在當前目錄下,能夠爲目錄所包含的當前項目代碼定製matplotlib配置項。配置文件的文件名是matplotlibrc
在Windows系統中,沒有全局配置文件,用戶配置文件的位置在C:\Documents and Settings\yourname\.matplotlib。
在Linux系統中,全局配置文件的位置在/etc/matplotlibrc,用戶配置文件的位置在$HOME/.matplotlib/matplotlibrc。
動態配置
程序中配置代碼
To finetune settings only for that execution; this overwrites every configuration file.
配置方法的優先級爲:
Matplotlib functions in Python code
matplotlibrc file in the current directory
User matplotlibrc file
Global matplotlibrc file
rcParams方法
經過rcParams字典訪問並修改全部已經加載的配置項
簡單的運用:
import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.rcParams['font.family']='SimHei' matplotlib.rcParams['font.sans-serif']=['SimHei'] labels=np.array(['第一次做業','第二次做業','第三次做業','第四次做業','第五次做業','第六次做業','第七次做業']) nAttr=7 data=np.array([0,0.909,1,1,1,0.875,0]) angles=np.linspace(0,2*np.pi,nAttr,endpoint=False) data=np.concatenate((data,[data[0]])) angles=np.concatenate((angles,[angles[0]])) fig=plt.figure(facecolor='white') plt.subplot(111,polar=True) plt.plot(angles,data,'bo-',color='g',linewidth=2) plt.fill(angles,data,facecolor='r',alpha=0.25) plt.thetagrids(angles*180/np.pi,labels) plt.figtext(0.52,0.95,'01個人成績',ha='center') plt.grid(True) plt.savefig('xuexi.JPG') plt.show()

結果圖:數組

 手繪風格:
from PIL import Image import numpy as np im0=np.array(Image.open('D:\\故宮.jpg').convert("L")) im1=255-im0 im2=(100/255)*im0+150 im3=255*(im1/255)**2 pil_im=Image.fromarray(np.uint(im1)) pil_im.save('gugonggai.jpg') pil_im.show()

im1,im2,im3三次改變的圖分別爲:ide

將im3改成:im3=255-255*(im1/255)**0.5+150函數

效果圖爲:工具

from PIL import Image import numpy as np vec_el=np.pi/2.2 vec_az=np.pi/4. depth=7. #顏色的深淺,建議不要寫太大的值,由於會變得很醜 im=np.array(Image.open('D:\\故宮.jpg').convert("L")) a=np.asanyarray(im).astype('float') grad=np.gradient(a) grad_x,grad_y=grad grad_x=grad_x*depth/100. grad_y=grad_y*depth/100. dx=np.cos(vec_el)*np.cos(vec_az) dy=np.cos(vec_el)*np.cos(vec_az) dz=np.sin(vec_el) A=np.sqrt(grad_x**2+grad_y**2+1.) uni_x=grad_x/A uni_y=grad_y/A uni_z=1./A a2=255*(dx*uni_x+dy*uni_y+dz*uni_z) a2=a2.clip(0,255) im2=Image.fromarray(a2.astype('uint8')) im2.save('gugong3.jpg')

 

好了,在這裏放一下原圖:性能

科學座標繪製ui

import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.rcParams['font.family']='SimHei' matplotlib.rcParams['font.sans-serif']=['SimHei'] def Draw(pcolor,nt_point,nt_text,nt_size): plt.plot(x,y,'k',label="$exp_decay$",color=pcolor,\ linewidth=3,linestyle="-") plt.plot(x,z,"b--",label="$cos(x^2)$",linewidth=1) plt.xlabel('時間(s)') plt.ylabel('幅度(mV)') plt.title("阻尼衰減曲線繪製") plt.annotate('$cos(2\pi t)\exp(-t)$',xy=nt_point,\ xytext=nt_text,fontsize=nt_size,arrowprops=\ dict(arrowstyle='->',connectionstyle="arc3,rad=.1")) def Shadow(a, b): ix=(x>a)&(x<b) plt.fill_between(x,y,0,where=ix,facecolor='grey',alpha=0.25) plt.text(0.5*(a+b),0.2,r"$\int_a^b f(x)\mathrm{d}x$",\ horizontalalignment='center') def XY_Axis(x_start,x_end,y_start,y_end): plt.xlim(x_start,x_end) plt.ylim(y_start,y_end) plt.xticks([np.pi/3,2*np.pi/3,1*np.pi,4*np.pi/3,\ 5*np.pi/3],['$\pi/3$','$2\pi/3$','$\pi$','$4\pi/3$','$5\pi/3$']) x=np.linspace(0.0,6.0,100) y=np.cos(2*np.pi*x)*np.exp(-x)+0.8 z=0.5*np.cos(x**2)+0.8 note_point,note_text,note_size=(1,np.cos(2*np.pi)*\ np.exp(-1)+0.8),(1,1.4),14 fig=plt.figure(figsize=(8,6),facecolor='white') plt.subplot(111) Draw("red",note_point,note_text,note_size) XY_Axis(0,5,0,1.8) Shadow(0.8, 3) plt.legend() plt.savefig('sample.jpg') plt.show()

結果圖爲:this

相關文章
相關標籤/搜索