科學計算和數據可視

[學習電子教案](https://2d.hep.com.cn/1865445/9)數組

科學計算可視化
 分類
​  信息可視化(信息、知識)瀏覽器

  科學可視化(空間數據)安全


 主要方法

  二維標量數據場
    顏色映射法
    等值線法
    立體圖法
    層次分割法
  三維標量數據場
    面繪製法
    體繪製法
    矢量數據場
    直接法
  用箭頭、線段、色輪等手段表示矢量數據
  流線法dom


應用領域函數

 

- 科學計算的基本概念
- numpy庫的使用
- matplotlib庫的使用
**1、科學計算的基本概念:**
科學計算須要採用矩陣運算庫numpy和繪製庫matplotlib
**2、numpy庫的使用:**
一、numpy庫概述:學習

**數據類型**:處理基礎數據類型爲同種元素構成的多維數組(ndarray)。
**索引**:數組中元素可用整數索引,序號從零開始。
**維度,軸,秩**:ndarray類型的維度(dimensions)叫作軸(axes),軸的個數叫作秩(rank)一維數組秩爲1,以此類推。
**引用**:
`import numpy as np`
二、numpy庫解析
1)numpy經常使用的數組(ndarray類型)建立函數(7個)
| 函數| 描述|
|--|--|
| np.array([x,y,z],dtype=int) |從Python列表和元組創造數組 |
| np.arange(x,y,i)| 建立一個從x到y,步長爲 i 的數組|
| np.linspace(x,y,n)|建立一個從x到y,等分紅 n 個元素的數組 |
|np.indices((m,n))|建立一個 m 行 n 列的矩陣|
|np.random.rand(m,n)|建立一個 m 行 n 列的隨機數組|
|np.ones((m,n),dtype)|建立一個 m 行 n 列全爲 1 的數組,dtype是數據類型|
|np.empty((m,n),dtype)|建立一個 m 行 n 列全爲0的數組,dtype是數據類型|
2)測試

三、示例:圖像的手繪效果
1)圖像的數組表示:
圖像是有規則的二維數組,能夠用numpy將圖像轉換成數組對象:ui

 1 #e17.1HandDrawPic.py
 2 from PIL import Image  3 import numpy as np  4 vec_el = np.pi/2.2 # 光源的俯視角度,弧度值
 5 vec_az = np.pi/4. # 光源的方位角度,弧度值
 6 depth = 10. # (0-100)
 7 im = Image.open('fcity.jpg').convert('L')  8 a = np.asarray(im).astype('float')  9 grad = np.gradient(a) #取圖像灰度的梯度值
10 grad_x, grad_y = grad #分別取橫縱圖像梯度值
11 grad_x = grad_x*depth/100. 12 grad_y = grad_y*depth/100. 13 dx = np.cos(vec_el)*np.cos(vec_az) #光源對x 軸的影響
14 dy = np.cos(vec_el)*np.sin(vec_az) #光源對y 軸的影響
15 dz = np.sin(vec_el) #光源對z 軸的影響
16 A = np.sqrt(grad_x**2 + grad_y**2 + 1.) 17 uni_x = grad_x/A 18 uni_y = grad_y/A 19 uni_z = 1./A 20 a2 = 255*(dx*uni_x + dy*uni_y + dz*uni_z) #光源歸一化
21 a2 = a2.clip(0,255) 22 im2 = Image.fromarray(a2.astype('uint8')) #重構圖像
23 im2.save('fcityHandDraw.jpg')

 


3、matplotlib庫的使用spa

實例1:基本三角函數圖像實現3d

 

1 import numpy as np 2 import matplotlib.pyplot as plt 3 x = np.linspace(0, 6, 100) 4 y = np.cos(2 * np.pi * x) * np.exp(-x)+0.8
5 plt.plot(x, y, 'k', color='r', linewidth=3, linestyle="-") 6 plt.show()

實例2:帶標識的座標系

 1 import matplotlib.pyplot as plt  2 import matplotlib  3 matplotlib.rcParams['font.family']='SimHei'
 4 matplotlib.rcParams['font.sans-serif'] = ['SimHei']  5 plt.plot([1,2,4], [1,2,3])  6 plt.title("座標系標題")  7 plt.xlabel('時間 (s)')  8 plt.ylabel('範圍 (m)')  9 plt.xticks([1,2,3,4,5],[r'$\pi/3$', r'$2\pi/3$', r'$\pi$',\ 10                    r'$4\pi/3$', r'$5\pi/3$'])
11 plt.show()

實例3:帶陰影的座標系

 1 import matplotlib.pyplot as plt  2 import numpy as np  3 x = np.linspace(0, 10, 1000)  4 y = np.cos(2*np.pi*x) * np.exp(-x)+0.8
 5 plt.plot(x,y,'k',color='r',label="$exp-decay$",linewidth=3)  6 plt.axis([0,6,0,1.8])  7 ix = (x>0.8) & (x<3)  8 plt.fill_between(x, y ,0, where = ix,  9                          facecolor='grey', alpha=0.25) 10 plt.text(0.5*(0.8+3), 0.2, r"$\int_a^b f(x)\mathrm{d}x$", 11                 horizontalalignment='center') 12 plt.legend() 13 plt.show()

實例4:帶阻尼衰減曲線座標圖繪製

 1 ##e18.1PlotDamping.py
 2 import numpy as np  3 import matplotlib.pyplot as plt  4 import matplotlib  5 matplotlib.rcParams['font.family']='SimHei'
 6 matplotlib.rcParams['font.sans-serif'] = ['SimHei']  7 def Draw(pcolor, nt_point, nt_text, nt_size):  8     plt.plot(x, y, 'k', label="$exp_decay$", color=pcolor, linewidth=3, linestyle="-")  9     plt.plot(x, z, "b--", label="$cos(x^2)$", linewidth=1) 10     plt.xlabel('時間(s)') 11     plt.ylabel('幅度(mV)') 12     plt.title("阻尼衰減曲線繪製") 13     plt.annotate('$\cos(2 \pi t) \exp(-t)$', xy=nt_point, xytext=nt_text, fontsize=nt_size,\ 14                arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.1")) 15 def Shadow(a, b): 16     ix = (x>a) & (x<b) 17     plt.fill_between(x,y,0,where=ix,facecolor='grey', alpha=0.25) 18     plt.text(0.5 * (a + b), 0.2, "$\int_a^b f(x)\mathrm{d}x$", \ 19              horizontalalignment='center') 20 def XY_Axis(x_start, x_end, y_start, y_end): 21  plt.xlim(x_start, x_end) 22  plt.ylim(y_start, y_end) 23     plt.xticks([np.pi/3, 2 * np.pi/3, 1 * np.pi, 4 * np.pi/3, 5 * np.pi/3], \ 24                ['$\pi/3$', '$2\pi/3$', '$\pi$', '$4\pi/3$', '$5\pi/3$']) 25 x = np.linspace(0.0, 6.0, 100) 26 y = np.cos(2 * np.pi * x) * np.exp(-x)+0.8
27 z = 0.5 * np.cos(x ** 2)+0.8
28 note_point,note_text,note_size = (1, np.cos(2 * np.pi) * np.exp(-1)+0.8),(1, 1.4), 14
29 fig = plt.figure(figsize=(8, 6), facecolor="white") 30 plt.subplot(111) 31 Draw("red", note_point, note_text, note_size) 32 XY_Axis(0, 5, 0, 1.8) 33 Shadow(0.8, 3) 34 plt.legend() 35 plt.savefig('sample.JPG') 36 plt.show()

實例5:多級雷達圖繪製
DOTA人物能力值雷達圖繪製

 1 #e19.1DrawRadar
 2 import numpy as np  3 import matplotlib.pyplot as plt  4 import matplotlib  5 matplotlib.rcParams['font.family']='SimHei'
 6 matplotlib.rcParams['font.sans-serif'] = ['SimHei']  7 labels = np.array(['綜合', 'KDA', '發育', '推動', '生存','輸出'])  8 nAttr = 6
 9 data = np.array([7, 5, 6, 9, 8, 7]) #數據值
10 angles = np.linspace(0, 2*np.pi, nAttr, endpoint=False) 11 data = np.concatenate((data, [data[0]])) 12 angles = np.concatenate((angles, [angles[0]])) 13 fig = plt.figure(facecolor="white") 14 plt.subplot(111, polar=True) 15 plt.plot(angles,data,'bo-',color ='g',linewidth=2) 16 plt.fill(angles,data,facecolor='g',alpha=0.25) 17 plt.thetagrids(angles*180/np.pi, labels) 18 plt.figtext(0.52, 0.95, 'DOTA能力值雷達圖', ha='center') 19 plt.grid(True) 20 plt.show()

實例6:霍蘭德人格分析雷達圖繪製

 1 #HollandRadarDraw.py
 2 from numpy import array,shape,arange  3 import numpy as np  4 import matplotlib.pyplot as plt  5 import matplotlib  6 matplotlib.rcParams['font.family']='SimHei'
 7 radar_labels = np.array(['研究型(I)','藝術型(A)','社會型(S)',\  8                          '企業型(E)','常規型(C)','現實型(R)']) #雷達標籤
 9 nAttr = 6
10 data = np.array([[0.40, 0.32, 0.35, 0.30, 0.30, 0.88], 11                  [0.85, 0.35, 0.30, 0.40, 0.40, 0.30], 12                  [0.43, 0.89, 0.30, 0.28, 0.22, 0.30], 13                  [0.30, 0.25, 0.48, 0.85, 0.45, 0.40], 14                  [0.20, 0.38, 0.87, 0.45, 0.32, 0.28], 15                  [0.34, 0.31, 0.38, 0.40, 0.92, 0.28]]) #數據值
16 data_labels = ('藝術家', '實驗員', '工程師', '推銷員', '社會工做者','記事員') 17 angles = np.linspace(0, 2*np.pi, nAttr, endpoint=False) 18 data = np.concatenate((data, [data[0]])) 19 angles = np.concatenate((angles, [angles[0]])) 20 fig = plt.figure(facecolor="white") 21 plt.subplot(111, polar=True) 22 plt.plot(angles,data,'o-', linewidth=1, alpha=0.2) 23 plt.fill(angles,data, alpha=0.25) 24 plt.thetagrids(angles*180/np.pi, radar_labels) 25 plt.figtext(0.52, 0.95, '霍蘭德人格分析', ha='center', size=20) 26 legend = plt.legend(data_labels, loc=(0.94, 0.80), labelspacing=0.1) 27 plt.setp(legend.get_texts(), fontsize='large') 28 plt.grid(True) 29 plt.savefig('holland_radar.jpg')

 

4、自定義手繪風

 

 1 #e17.1HandDrawPic.py
 2 from PIL import Image  3 import numpy as np  4 vec_el = np.pi/2.2 # 光源的俯視角度,弧度值
 5 vec_az = np.pi/4. # 光源的方位角度,弧度值
 6 depth = 10. # (0-100)
 7 im = Image.open('D:\\360安全瀏覽器下載\xiaomanyao.jpg').convert('L')  8 a = np.asarray(im).astype('float')  9 grad = np.gradient(a) #取圖像灰度的梯度值
10 grad_x, grad_y = grad #分別取橫縱圖像梯度值
11 grad_x = grad_x*depth/100. 12 grad_y = grad_y*depth/100. 13 dx = np.cos(vec_el)*np.cos(vec_az) #光源對x 軸的影響
14 dy = np.cos(vec_el)*np.sin(vec_az) #光源對y 軸的影響
15 dz = np.sin(vec_el) #光源對z 軸的影響
16 A = np.sqrt(grad_x**2 + grad_y**2 + 1.) 17 uni_x = grad_x/A 18 uni_y = grad_y/A 19 uni_z = 1./A 20 a2 = 255*(dx*uni_x + dy*uni_y + dz*uni_z) #光源歸一化
21 a2 = a2.clip(0,255) 22 im2 = Image.fromarray(a2.astype('uint8')) #重構圖像
23 im2.save('D:\\360安全瀏覽器下載\xaiomanyaoHandDraw.jpg')

**5、模仿實例對本身的成績進行分析:**

 

 1 import numpy as np  2 import matplotlib.pyplot as plt  3 import matplotlib  4 matplotlib.rcParams['font.family']='SimHei'
 5 matplotlib.rcParams['font.sans-serif'] = ['SimHei']  6 labels = np.array(['第一次', '第二次', '第三次', '第四次', '第五次'])  7 nAttr = 5
 8 data = np.array([20,15,17,18,10]) #數據值
 9 angles = np.linspace(0, 2*np.pi, nAttr, endpoint=False) 10 data = np.concatenate((data, [data[0]])) 11 angles = np.concatenate((angles, [angles[0]])) 12 fig = plt.figure(facecolor="white") 13 plt.subplot(111, polar=True) 14 plt.plot(angles,data,'bo-',color ='g',linewidth=2) 15 plt.fill(angles,data,facecolor='g',alpha=0.25) 16 plt.thetagrids(angles*180/np.pi, labels) 17 plt.figtext(0.52, 0.95, '舒新城的博客測試分析', ha='center') 18 plt.grid(True) 19 plt.show()

 

6、繪製一個數學規律圖:用極座標方程繪製圓錐曲線:

1 import numpy as py 2 import matplotlib.pyplot as plt 3 i=np.linspace(0,2*np.pi,100) 4 x=a*np.sin(i) 5 y=b*np.cos(i) 6 plt.plot(x,y,'k',color='r',linewidth='10',linestyle="-") 7 plt.show()

 7、運用pandas庫處理Excel文件數據

相關文章
相關標籤/搜索