matplotlib 畫圖

matplotlib 畫圖

 

1. 畫曲線圖html

  1.  
     
  2.  
    Tompson = np.array([ 0, 0, 0, 0, 0.011, 0.051, 0.15, 0.251, 0.35, 0.44, 0.51, 0.59, 0.65, 0.68, 0.725, 0.752, 0.8])
  3.  
    ours = np.array([ 0.00000000e+00, 1.21182744e-04, 4.26563257e-02,
  4.  
    1.76078526e-01, 3.51187591e-01, 5.02666020e-01,
  5.  
    6.18274358e-01, 7.03102278e-01, 7.61754726e-01,
  6.  
    8.12893844e-01, 8.63427048e-01, 9.02205526e-01,
  7.  
    9.30198740e-01, 9.51284537e-01, 9.61706253e-01,
  8.  
    9.74066893e-01, 9.79641299e-01])
  9.  
    Deep_prior = np.array([ 0, 0, 0.03, 0.09, 0.15, 0.251, 0.34, 0.415, 0.49, 0.55, 0.62, 0.69, 0.74, 0.79, 0.83, 0.86, 0.9])
  10.  
    Zhou = np.array([ 0, 0, 0.023, 0.1, 0.21, 0.325, 0.415, 0.52, 0.59, 0.661, 0.73, 0.78, 0.85, 0.885, 0.91, 0.94, 0.95])
  11.  
    Feedback_loop = np.array(
  12.  
        [ 0, 0, 0.022, 0.09, 0.20, 0.32, 0.415, 0.53, 0.642, 0.72, 0.79, 0.85, 0.88, 0.91, 0.951, 0.96, 0.965])
  13.  
    Crossing_net = np.array(
  14.  
        [ 0, 0, 0.07, 0.17, 0.25, 0.36, 0.485, 0.62, 0.715, 0.79, 0.865, 0.906, 0.92, 0.95, 0.952, 0.970, 0.97])
  15.  
    qinghua = np.array([ 0.        ,  0.00121183,  0.06386331,  0.17886573,  0.3427048 ,
  16.  
            0.4655841 ,  0.57828405,  0.67716917,  0.76223946,  0.82222492,
  17.  
            0.87433349,  0.91250606,  0.94122637,  0.96122152,  0.9726127 ,
  18.  
            0.9831556 ,  0.98679108])
  19.  
    def draw_map(errs1, errs2, errs3, errs4, errs5, errs6, errs7):
  20.  
        # err_flat = errs.ravel()  # Return a flattened array, 相同功能的函數爲np.flat
  21.  
        thresholds = np.arange( 0, 85, 5)  # 不包含85
  22.  
        fig=plt.figure(figsize=( 10, 8)) # 設置figsize的大小
  23.  
        ax = fig.add_subplot( 111)
  24.  
        ax.plot(thresholds, errs1, '-.', thresholds, errs2, '-_',
  25.  
                 thresholds, errs3, '--', thresholds, errs4, '--*', thresholds, errs5, ':*',
  26.  
                 thresholds, errs6, ':x', linewidth=2)
  27.  
        ax.plot(thresholds, errs7, '-', linewidth=2.25, color='b')
  28.  
        ax.set_xlabel( 'Maximum joint error threshold (mm)', fontsize=15)
  29.  
        ax.set_ylabel( 'Fraction of frames within threshold', fontsize=15)
  30.  
        ax.tick_params(axis= 'x', labelsize=15)
  31.  
        ax.tick_params(axis= 'y', labelsize=15)    
  32.  
    #     設置x, y軸的數字字號    
  33.  
    #     plt.rcParams['xtick.labelsize']=15
  34.  
    #     plt.rcParams['ytick.labelsize']=15
  35.  
    #     或者   
  36.  
    #     plt.set_xticks(fontsize=15)  # 設置座標軸刻度字體大小
  37.  
    #     plt.set_yticks(fontsize=15)
  38.  
        ax.legend([ 'Tompson et al.', 'Prior', 'Zhou et al.', 'Feedback',  'REN', 'Crossing Nets','ours'], loc='lower right',
  39.  
                   prop={ 'size': 15})
  40.  
        ax.grid( True)
  41.  
     
  42.  
    fig=draw_map(Tompson, Deep_prior, Zhou, Feedback_loop, qinghua, Crossing_net, ours)
  43.  
     
  44.  
     

 

 

[py]  view plain  copy
 
  1. <span style="font-size:18px">  
  2. plt.savefig('D:\\filename.svg',format='svg')  #保持爲eps格式或者svg格式  
  3. plt.show()</span>  

 

 

 前面依然使用plt句柄,只是最後獲取當前圖像python

 

  1.  
    # plt調用gcf函數取得當前繪製的figure並調用savefig函數
  2.  
    foo_fig = plt.gcf() # 'get current figure'
  3.  
    foo_fig.savefig( 'foo.eps', format='eps', dpi=1000)
  4.  
    plt.show()

2. 畫柱狀圖api

 

  1.  
    def draw_error(errs1, errs2, errs3, errs4, errs5, errs6, dataset='nyu'):
  2.  
    bar_width = 0.23
  3.  
    opacity = 0.4
  4.  
    # 將整體的mean計算出來也放進去!!
  5.  
    if dataset == 'icvl':
  6.  
    joint_idx = [ 0, 1, 3, 4, 6, 7, 9, 10, 12, 13, 15, 16]
  7.  
    names = [ 'Palm', 'Thumb.R', 'Thumb.T', 'Index.R', 'Index.T', 'Mid.R', 'Mid.T', 'Ring.R', 'Ring.T', 'Pinky.R',
  8.  
    'Pinky.T', 'Mean']
  9.  
    elif dataset == 'nyu':
  10.  
    joint_idx = [ 0, 1, 2, 3, 4, 5, 6, 7, 13, 11, 12, 8, 9, 10, 14]
  11.  
    names = [ 'P1', 'P2', 'R1', 'R2', 'M1', 'M2', 'I1', 'I2', 'C', 'W1', 'W2', 'T1', 'T2', 'T3', 'AVG']
  12.  
     
  13.  
    x = np.arange(len(joint_idx))
  14.  
    plt.figure(figsize=( 12, 8))
  15.  
    # plt.bar(x, errs1[joint_idx]) # 選中indx爲joint_idx的元素
  16.  
    # plt.title('error')
  17.  
    plt.xticks(x + 0.5, names, fontsize=15) # set the locations and labels of the xticks , rotation='vertical'
  18.  
    plt.yticks(fontsize= 15) # 設置座標軸刻度字體大小
  19.  
    plt.ylabel( 'Mean Error (mm)', fontsize=15)
  20.  
    # plt.grid(True)
  21.  
     
  22.  
    rects1 = plt.bar(x, errs1, bar_width / 2, alpha=opacity, color='y', label='Tompson et al.')
  23.  
    rects2 = plt.bar(x + bar_width / 2, errs2, bar_width / 2, alpha=opacity, color='k', label='Prior')
  24.  
     
  25.  
    rects3 = plt.bar(x + bar_width, errs3, bar_width / 2, alpha=opacity, color='c', label='Zhou et al.')
  26.  
    rects4 = plt.bar(x + 1.5 * bar_width, errs4, bar_width / 2, alpha=opacity, color='m', label='Feedback')
  27.  
    rects5 = plt.bar(x + 2 * bar_width, errs5[joint_idx], bar_width / 2, alpha=opacity, color='g', label='REN')
  28.  
    rects6 = plt.bar(x + 2.5 * bar_width, errs6[joint_idx], bar_width / 2, alpha=opacity, color='b', label='ours')
  29.  
     
  30.  
    plt.legend(loc= 'upper left', prop={'size': 12})
  31.  
    plt.tight_layout()
  32.  
    foo_fig = plt.gcf() # 'get current figure'
  33.  
    foo_fig.savefig( '柱狀圖.eps', format='eps', dpi=1000)
  34.  
    plt.show()

3. 轉載的一個教程: 點擊打開連接數組

 

官網介紹:

 

matplotlib APIdom

一個很詳細的博客:

matplotlib繪圖基礎ide

漂亮插圖demosvg

基礎知識:

首先一幅Matplotlib的圖像組成部分介紹。函數

在matplotlib中,整個圖像爲一個Figure對象。在Figure對象中能夠包含一個或者多個Axes對象。每一個Axes(ax)對象都是一個擁有本身座標系統的繪圖區域。所屬關係以下:oop

下面以一個直線圖來詳解圖像內部各個組件內容:post

其中:title爲圖像標題,Axis爲座標軸, Label爲座標軸標註,Tick爲刻度線,Tick Label爲刻度註釋。各個對象關係能夠梳理成如下內容:

圖像中全部對象均來自於Artist的基類。

上面基本介紹清楚了圖像中各個部分的基本關係,下面着重講一下幾個部分的詳細的設置。

一個"Figure"意味着用戶交互的整個窗口。在這個figure中容納着"subplots"。

當咱們調用plot時,matplotlib會調用gca()獲取當前的axes繪圖區域,並且gca反過來調用gcf()來得到當前的figure。若是figure爲空,它會自動調用figure()生成一個figure, 嚴格的講,是生成subplots(111)

Figures

Subplots

  1.  
    plt.subplot(221) # 第一行的左圖
  2.  
    plt.subplot(222) # 第一行的右圖
  3.  
    plt.subplot(212) # 第二整行
  4.  
    plt.show()

注意:其中各個參數也能夠用逗號,分隔開。第一個參數表明子圖的行數;第二個參數表明該行圖像的列數; 第三個參數表明每行的第幾個圖像。

另外:fig, ax = plt.subplots(2,2),其中參數分別表明子圖的行數和列數,一共有 2x2 個圖像。函數返回一個figure圖像和一個子圖ax的array列表。

補充:gridspec命令能夠對子圖區域劃分提供更靈活的配置。

中文顯示方框問題

這是因爲matplotlib文件夾內沒有中文字體包致使的,實際上函數包自己是支持中文的,常看法決方案是拷貝字體文件到matplotlib中,不過我感受太麻煩,找到了另外的方式,

1
2
3
4
from  pylab  import  mpl
 
mpl.rcParams[ 'font.sans-serif' =  [ 'FangSong' ]     # 指定默認字體
mpl.rcParams[ 'axes.unicode_minus' =  False         # 解決保存圖像是負號'-'顯示爲方塊的問題  

加上這三行代碼指定一下字體就好了(實際上最後一行能夠不加)

經常使用繪製流程

1.axes列表中包含各個子圖句柄

1
2
3
4
5
6
7
# 3x3子圖
fig, axes  =  plt.subplots( 3 3 )
# 子圖間距設定
fig.subplots_adjust(hspace = 0.3 , wspace = 0.3 )
# 在分別繪製各個子圖
for  i, ax  in  enumerate (axes.flat):
     pass

2.每一個子圖句柄須要單獨生成

1
2
3
4
5
6
7
8
# 畫布
fig  =  plt.figure()
# 添加子圖
ax  =  fig.add_subplot( 211 )
pass
# 添加子圖
ax2  =  fig.add_subplot( 212 )
pass

3.使用plt包命名空間代指多個子圖句柄

【注】這種方法的句柄含在plt中,與上面的ax的方法屬性並不相同,下面會詳解

1
2
3
4
5
6
7
8
9
# 添加子圖
plt.subplot( 311 )
pass
# 添加子圖
plt.subplot( 312 )
pass
# 添加子圖
plt.subplot( 313 )
pass

繪圖功能

【注】使用ax代指子圖方法一、2的句柄,plt代指方法3中的命名空間。座標生成:

1
2
3
4
5
6
# 一維座標生成
=  np.linspace( 0 , 10 , 100 )
 
# 二維網格生成
=  np.linspace( - 1 , 1 , 100 )
x,y  =  np.meshgrid(u,u)

 座標軸標籤:

1
2
3
4
5
6
7
8
xlabel  =  "True: {0}, Pred: {1}" . format (cls_true[i], cls_pred[i])
xlabel  =  "y"
 
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
 
plt.xlabel( 'x' )
plt.ylabel( 'y' )

 座標軸刻度:

1
2
3
4
5
ax.set_xticks([])
ax.set_yticks([])
 
plt.xticks( range ( len (x)), [ 'a' 'b' 'c' 'd' 'e' 'f' ])
plt.yticks( range ( 1 8 2 ))

 座標網格:

1
2
3
4
5
6
7
# 橫縱座標單位長度統一
plt.axis( 'equal' )
# 網格
plt.grid( True )
 
# 網格
ax.grid( True )

 圖表標題:

1
plt.title( 'Second Derivative' )

 對數座標:

1
2
3
4
5
'''對數座標'''
 
plt.semilogx(x,y)   # 對x取對數
plt.semilogy(x,y)   # 對y取對數
plt.loglog(x,y)     # 同時取對數

繪圖:

1
2
3
4
5
6
7
8
9
10
# 色彩填充
ax.fill(x,y1,facecolor = 'g' ,alpha = 0.3 )
ax.fill_between(x,y,y1,facecolor = 'b' )
# 等高線
ax.contourf(x,y,z)
# 顯示數組,由於是數組因此纔會有vmin和vmax的關鍵字
ax.imshow()
 
# 線性繪圖
plt.plot(x,y1,c = 'b' ,linestyle = ' ',marker=' ^')

經典實現

餅狀圖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import  matplotlib.pyplot as plt
 
plt.figure(figsize = ( 12 , 9 ))
 
labels  =  [ 'part1' 'part2' 'part3' ]
# 各個餅的比例
sizes  =  [ 30 20 50 ]
colors  =  [ 'yellowgreen' 'gold' 'lightskyblue' ]
 
# 各個模塊離圓心的距離,參數爲距離
explode  =  ( 0.05 0.0 0.0
# 圖 label的text 比例的text
patches, l_texts, p_texts  =  plt.pie(sizes, explode = explode, labels = labels, colors = colors, labeldistance = 0.8 ,
         autopct = '%3.1f%%' , shadow = True , startangle = 90 , pctdistance = 0.6 )
 
# 設置x,y軸刻度一致,這樣餅圖才能是圓的
plt.axis( 'equal' )
plt.legend()
 
# 設置label的字體大小
for  in  l_texts:
     t.set_size( 20 )
# 設置比例數字的字體大小
for  in  p_texts:
     t.set_size( 20 )
 
plt.show()

 

柱狀圖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import  numpy as np
from  matplotlib  import  pyplot as plt
 
plt.figure(figsize = ( 9 , 6 ))
 
=  12
=  np.arange(n) + 1
# numpy.random.uniform(low=0.0, high=1.0, size=None), normal
Y1  =  ( 1 - X / float (n + 1 ))  *  np.random.uniform( 0.5 , 1.0 ,n)
Y2  =  ( 1 - X / float (n + 1 ))  *  np.random.uniform( 0.5 , 1.0 ,n)
 
# bar and barh
width  =  0.35
plt.bar(X, Y1, width = width, facecolor = '#9999ff' , edgecolor = 'white' )
plt.bar(X + width, Y2, width = width, facecolor = '#ff9999' , edgecolor = 'white' )
plt.bar(X,  - Y2, width = width, facecolor = '#ff9999' , edgecolor = 'white' )
 
# 柱狀圖添加說明文字
for  x,y  in  zip (X,Y1):
     plt.text(x, y + 0.05 '%.2f'  %  y, ha = 'center' , va =  'bottom' )
     
for  x,y  in  zip (X, - Y2):
     plt.text(x + 0.4 , y - 0.15 '%.2f'  %  y, ha = 'center' , va =  'bottom' )
 
#plt.ylim(-1.25,+1.25)
plt.show()

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import  numpy as np
from  matplotlib  import  pyplot as plt
 
plt.figure(figsize = ( 9 , 6 ))
 
=  12
=  np.arange(n) + 1
# numpy.random.uniform(low=0.0, high=1.0, size=None), normal
Y1  =  ( 1 - X / float (n + 1 ))  *  np.random.uniform( 0.5 , 1.0 ,n)
Y2  =  ( 1 - X / float (n + 1 ))  *  np.random.uniform( 0.5 , 1.0 ,n)
 
# bar and barh
width  =  0.35
# 方法barh和參數height能夠實現橫向的柱狀圖
plt.barh(X, Y1, height = width, facecolor = '#9999ff' , edgecolor = 'white' )
 
plt.show()

 

機率分佈圖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from  matplotlib  import  pyplot as plt
import  numpy as np
 
mu  =  0
sigma  =  1
=  mu  +  sigma * np.random.randn( 10000 )
 
fig,(ax0,ax1) = plt.subplots(ncols = 2 , figsize = ( 9 , 6 ))
 
ax0.hist(x,  20 , normed = 1 , histtype = 'bar' , facecolor = 'g' , rwidth = 0.8 , alpha = 0.75 )
ax0.set_title( 'pdf' )
# 累積機率密度分佈
ax1.hist(x,  20 , normed = 1 , histtype = 'bar' , rwidth = 0.8 , cumulative = True )
ax1.set_title( 'cdf' )
 
plt.show()

 

散點圖

atan2(a,b)是4象限反正切,它的取值不只取決於正切值a/b,還取決於點 (b, a) 落入哪一個象限: 當點(b, a) 落入第一象限時,atan2(a,b)的範圍是 0 ~ pi/2;  當點(b, a) 落入第二象限時,atan2(a,b)的範圍是 pi/2 ~ pi; 當點(b, a) 落入第三象限時,atan2(a,b)的範圍是 -pi~-pi/2;  當點(b, a) 落入第四象限時,atan2(a,b)的範圍是 -pi/2~0

而 atan(a/b) 僅僅根據正切值爲a/b求出對應的角度 (能夠看做僅僅是2象限反正切): 當 a/b > 0 時,atan(a/b)取值範圍是 0 ~ pi/2; 當 a/b < 0 時,atan(a/b)取值範圍是 -pi/2~0

故 atan2(a,b) = atan(a/b) 僅僅發生在 點 (b, a) 落入第一象限 (b>0, a>0)或 第四象限(b>0, a0 , 故 atan(a/b) 取值範圍是 0 ~ pi/2,2atan(a/b) 的取值範圍是 0 ~ pi,而此時atan2(a,b)的範圍是 -pi~-pi/2,很顯然,atan2(a,b) = 2atan(a/b)

舉個最簡單的例子,a = 1, b = -1,則 atan(a/b) = atan(-1) = -pi/4, 而 atan2(a,b) = 3*pi/4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from  matplotlib  import  pyplot as plt
import  numpy as np
 
plt.figure(figsize = ( 9 , 6 ))
 
=  1024
 
# 均勻分佈 高斯分佈
# rand 和 randn
=  np.random.rand( 1 ,n)
=  np.random.rand( 1 ,n)
 
# 設定顏色
=  np.arctan2(Y,X)
 
plt.scatter(X,Y, s = 75 , c = T, alpha = . 4 , marker = 'o' )
 
#plt.xlim(-1.5,1.5), plt.xticks([])
#plt.ylim(-1.5,1.5), plt.yticks([])
 
plt.show()

 

不規則組合圖

# 定義子圖區域
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left + width + 0.02

rect_scatter = [left, bottom, width, height]
rect_histx = [left, bottom_h, width, 0.2]
rect_histy = [left_h, bottom, 0.2, height]

plt.figure(1, figsize=(6, 6))

# 須要傳入[左邊起始位置,下邊起始位置,寬,高]
# 根據子圖區域來生成子圖
axScatter = plt.axes(rect_scatter)
axHistx = plt.axes(rect_histx)
axHisty = plt.axes(rect_histy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# ref : http://matplotlib.org/examples/pylab_examples/scatter_hist.html
 
import  numpy as np
import  matplotlib.pyplot as plt
 
# the random data
=  np.random.randn( 1000 )
=  np.random.randn( 1000 )
 
# 定義子圖區域
left, width  =  0.1 0.65
bottom, height  =  0.1 0.65
bottom_h  =  left_h  =  left  +  width  +  0.02
 
rect_scatter  =  [left, bottom, width, height]
rect_histx  =  [left, bottom_h, width,  0.2 ]
rect_histy  =  [left_h, bottom,  0.2 , height]
 
plt.figure( 1 , figsize = ( 6 6 ))
 
# 根據子圖區域來生成子圖
axScatter  =  plt.axes(rect_scatter)
axHistx  =  plt.axes(rect_histx)
axHisty  =  plt.axes(rect_histy)
 
# no labels
#axHistx.xaxis.set_ticks([])
#axHisty.yaxis.set_ticks([])
 
# now determine nice limits by hand:
N_bins = 20
xymax  =  np. max ([np. max (np.fabs(x)), np. max (np.fabs(y))])
binwidth  =  xymax / N_bins
lim  =  ( int (xymax / binwidth)  +  1 *  binwidth
nlim  =  - lim
 
# 畫散點圖,機率分佈圖
axScatter.scatter(x, y)
axScatter.set_xlim((nlim, lim))
axScatter.set_ylim((nlim, lim))
 
bins  =  np.arange(nlim, lim  +  binwidth, binwidth)
axHistx.hist(x, bins = bins)
axHisty.hist(y, bins = bins, orientation = 'horizontal' )
 
# 共享刻度
axHistx.set_xlim(axScatter.get_xlim())
axHisty.set_ylim(axScatter.get_ylim())
 
plt.show()

 

三維數據圖

使用散點圖的點大小、顏色、透明度表示高維數據:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import  numpy as np
import  matplotlib.pyplot as plt
 
fig  =  plt.figure(figsize = ( 9 , 6 ),facecolor = 'white' )
 
# Number of ring
=  50
size_min  =  50
size_max  =  50 * 50
 
# Ring position
=  np.random.rand(n, 2 )
 
# Ring colors R,G,B,A
=  np.ones((n, 4 ))  *  ( 0.5 , 0.5 , 0 , 1 )
# Alpha color channel goes from 0 (transparent) to 1 (opaque),很厲害的實現
C[:, 3 =  np.linspace( 0 , 1 ,n)
 
# Ring sizes
=  np.linspace(size_min, size_max, n)
 
# Scatter plot
plt.scatter(P[:, 0 ], P[:, 1 ], s = S, lw  =  0.5 ,
                   edgecolors  =  C, facecolors = C)
 
plt.xlim( 0 , 1 ), plt.xticks([])
plt.ylim( 0 , 1 ), plt.yticks([])
 
plt.show()

 

美化

1
2
3
4
5
6
7
8
# 美化matplotlib繪出的圖,導入後自動美化
import  seaborn as sns
 
# matplotlib自帶美化風格
# 打印可選風格
print (plt.style.available  #ggplot, bmh, dark_background, fivethirtyeight, grayscale)
# 激活風格
plt.style.use( 'bmh' )

一維顏色填充 & 三維繪圖 & 三維等高線圖

『Python』Numpy學習指南第九章_使用Matplotlib繪圖

from mpl_toolkits.mplot3d import Axes3D

ax = fig.add_subplot(111,projection='3d')

ax.plot() 繪製3維線

ax.plot_surface繪製三維網格(面)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from  mpl_toolkits.mplot3d  import  Axes3D    #<-----導入3D包
import  numpy as np
import  matplotlib.pyplot as plt
 
fig  =  plt.figure(figsize = ( 9 , 6 ))
ax  =  fig.add_subplot( 111 ,projection = '3d' #<-----設置3D模式子圖
<br> # 新思路,以前都是生成x和y繪製z=f(x,y)的函數,此次繪製x=f1(z),y=f2(z)
=  np.linspace( 0 6 1000 )
=  1
=  *  np.sin(np.pi * 2 * z)
=  *  np.cos(np.pi * 2 * z)
 
ax.plot(x, y, z, label = u '螺旋線' , c = 'r' )
ax.legend()
 
# dpi每英寸長度的點數
plt.savefig( '3d_fig.png' ,dpi = 200 )
plt.show()

 

 # ax.plot 繪製的是3維線,ax.plot_surface繪製的是三維網格(也就是面)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from  mpl_toolkits.mplot3d  import  axes3d
import  matplotlib.pyplot as plt
from  matplotlib  import  cm
 
fig  =  plt.figure()
ax  =  fig.add_subplot( 111 ,projection = '3d' )
X, Y, Z  =  axes3d.get_test_data( 0.05 )
print (X,Y,Z)
# ax.plot 繪製的是3維線,ax.plot_surface繪製的是三維網格(也就是面)
ax.plot_surface(X, Y, Z, rstride = 5 , cstride = 5 , alpha = 0.3 )
# 三維圖投影製做,zdir選擇投影方向座標軸
cset  =  ax.contour(X, Y, Z,  10 , zdir = 'z' , offset = - 100 , cmap = cm.coolwarm)
cset  =  ax.contour(X, Y, Z, zdir = 'x' , offset = - 40 , cmap = cm.coolwarm)
cset  =  ax.contour(X, Y, Z, zdir = 'y' , offset = 40 , cmap = cm.coolwarm)
 
ax.set_xlabel( 'X' )
ax.set_xlim( - 40 40 )
ax.set_ylabel( 'Y' )
ax.set_ylim( - 40 40 )
ax.set_zlabel( 'Z' )
ax.set_zlim( - 100 100 )
 
plt.show()

 

 

 

 # 爲等高線圖添加標註

1
2
cs  =  ax2.contour(X,Y,Z)
ax2.clabel(cs, inline = 1 , fontsize = 5 )

 

 

配置Colorbar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# -*- coding: utf-8 -*- 
#********************************************************** 
import  os 
import  numpy as np 
import  wlab  #pip install wlab 
import  matplotlib 
import  matplotlib.cm as cm 
import  matplotlib.pyplot as plt 
from  matplotlib.ticker  import  MultipleLocator 
from  scipy.interpolate  import  griddata 
matplotlib.rcParams[ 'xtick.direction' =  'out' 
matplotlib.rcParams[ 'ytick.direction' =  'out' 
#********************************************************** 
FreqPLUS = [ 'F06925' , 'F10650' , 'F23800' , 'F18700' , 'F36500' , 'F89000'
FindPath = '/d3/MWRT/R20130805/' 
#********************************************************** 
fig  =  plt.figure(figsize = ( 8 , 6 ), dpi = 72 , facecolor = "white"
axes  =  plt.subplot( 111
axes.cla() #清空座標軸內的全部內容 
#指定圖形的字體 
font  =  { 'family'  'serif'
         'color'   'darkred'
         'weight'  'normal'
         'size'    16
        
#********************************************************** 
# 查找目錄總文件名中保護F06925,EMS和txt字符的文件 
for  fp  in  FreqPLUS: 
     FlagStr = [fp, 'EMS' , 'txt'
     FileList = wlab.GetFileList(FindPath,FlagStr) 
    
     LST = [] #地表溫度 
     EMS = [] #地表發射率 
     TBH = [] #水平極化亮溫 
     TBV = [] #垂直極化亮溫 
    
     findex = 0 
     for  fn  in  FileList: 
         findex = findex + 1 
         if  (os.path.isfile(fn)): 
             print ( str (findex) + '-->' + fn) 
             #fn='/d3/MWRT/R20130805/F06925_EMS60.txt' 
             data = wlab.dlmread(fn) 
             EMS = EMS + list (data[:, 1 ]) #地表發射率 
             LST = LST + list (data[:, 2 ]) #溫度 
             TBH = TBH + list (data[:, 8 ]) #水平亮溫 
             TBV = TBV + list (data[:, 9 ]) #垂直亮溫 
     #----------------------------------------------------------- 
     #生成格點數據,利用griddata插值 
     grid_x, grid_y  =  np.mgrid[ 275 : 315 : 1 0.60 : 0.95 : 0.01
     grid_z  =  griddata((LST,EMS), TBH, (grid_x, grid_y), method = 'cubic'
     #將橫縱座標都映射到(0,1)的範圍內 
     extent = ( 0 , 1 , 0 , 1
      #指定colormap 
     cmap  =  matplotlib.cm.jet 
     #設定每一個圖的colormap和colorbar所表示範圍是同樣的,即歸一化 
     norm  =  matplotlib.colors.Normalize(vmin = 160 , vmax = 300
     #顯示圖形,此處沒有使用contourf #>>>ctf=plt.contourf(grid_x,grid_y,grid_z) 
     gci = plt.imshow(grid_z.T, extent = extent, origin = 'lower' ,cmap = cmap, norm = norm) 
     #配置一下座標刻度等 
     ax = plt.gca() 
     ax.set_xticks(np.linspace( 0 , 1 , 9 )) 
     ax.set_xticklabels( ( '275' '280' '285' '290' '295' ,   '300' ,   '305' ,   '310' '315' )) 
     ax.set_yticks(np.linspace( 0 , 1 , 8 )) 
     ax.set_yticklabels( ( '0.60' '0.65' '0.70' '0.75' '0.80' , '0.85' , '0.90' , '0.95' )) 
     #顯示colorbar 
     cbar  =  plt.colorbar(gci) 
     cbar.set_label( '$T_B(K)$' ,fontdict = font) 
     cbar.set_ticks(np.linspace( 160 , 300 , 8 )) 
     cbar.set_ticklabels( ( '160' '180' '200' '220' '240' ,   '260' ,   '280' ,   '300' )) 
     #設置label 
     ax.set_ylabel( 'Land Surface Emissivity' ,fontdict = font) 
     ax.set_xlabel( 'Land Surface Temperature(K)' ,fontdict = font)  #陸地地表溫度LST 
     #設置title 
     titleStr = '$T_B$ for Freq = ' + str ( float (fp[ 1 : - 1 ]) * 0.01 ) + 'GHz' 
     plt.title(titleStr) 
     figname = fp + '.png' 
     plt.savefig(figname) 
     plt.clf() #清除圖形 
   
#plt.show() 
print ( 'ALL -> Finished OK' )

上面的例子中,每一個保存的圖,都是用一樣的colormap,而且每一個圖的顏色映射值都是同樣的,也就是說第一個圖中若是200表示藍色,那麼其餘圖中的200也表示藍色。

示例的圖形以下:


 

4.  樣式美化(matplotlib.pyplot.style.use)  點擊打開連接

 

使用matplotlib自帶的幾種美化樣式,就能夠很輕鬆的對生成的圖形進行美化。

可使用matplotlib.pyplot.style.available獲取全部的美化樣式

 

[python]  view plain  copy
 
  1. #!/usr/bin/python  
  2. #coding: utf-8  
  3.   
  4. import numpy as np  
  5. import matplotlib.pyplot as plt  
  6.   
  7. # 獲取全部的自帶樣式  
  8. print plt.style.available  
  9.   
  10. # 使用自帶的樣式進行美化  
  11. plt.style.use("ggplot")  
  12.   
  13. fig, axes = plt.subplots(ncols = 2, nrows = 2)  
  14.   
  15. # 四個子圖的座標軸賦予四個對象  
  16. ax1, ax2, ax3, ax4 = axes.ravel()  
  17.   
  18. x, y = np.random.normal(size = (2, 100))  
  19. ax1.plot(x, y, "o")  
  20.   
  21. x = np.arange(1, 10)  
  22. y = np.arange(1, 10)  
  23.   
  24. # plt.rcParams['axes.prop_cycle']獲取顏色的字典  
  25. # 會在這個範圍內依次循環  
  26. ncolors = len(plt.rcParams['axes.prop_cycle'])  
  27. # print ncolors  
  28. # print plt.rcParams['axes.prop_cycle']  
  29.   
  30. shift = np.linspace(1, 20, ncolors)  
  31. for s in shift:  
  32.     # print s  
  33.     ax2.plot(x, y + s, "-")  
  34.   
  35. x = np.arange(5)  
  36. y1, y2, y3 = np.random.randint(1, 25, size = (3, 5))  
  37. width = 0.25  
  38.   
  39. # 柱狀圖中要顯式的指定顏色  
  40. ax3.bar(x, y1, width, color = "r")  
  41. ax3.bar(x + width, y2, width, color = "g")  
  42. ax3.bar(x + 2 * width, y3, width, color = "y")  
  43.   
  44. for i, color in enumerate(plt.rcParams['axes.prop_cycle']):  
  45.     xy = np.random.normal(size= 2)  
  46.     for c in color.values():  
  47.         ax4.add_patch(plt.Circle(xy, radius = 0.3, color= c))  
  48.   
  49. ax4.axis("equal")  
  50.   
  51. plt.show()  

使用ggplot進行美化後的結果

 

相關文章
相關標籤/搜索