『Matplotlib』數據可視化專項

1、相關知識

官網介紹

matplotlib APIhtml

相關博客

matplotlib繪圖基礎python

漂亮插圖demoapi

使用seaborn繪製漂亮的熱度圖數組

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

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

中文顯示方框問題

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

from pylab import mpl

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

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

anaconda字體路徑在:/anaconda2/lib/python2.7/site-packages/matplotlib/mpl-data/font/ttf學習

1、經常使用繪製流程

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

# 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.每一個子圖句柄須要單獨生成

# 畫布
fig = plt.figure()
# 添加子圖
ax = fig.add_subplot(211)
pass
# 添加子圖
ax2 = fig.add_subplot(212)
pass

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

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

# 添加子圖
plt.subplot(311)
pass
# 添加子圖
plt.subplot(312)
pass
# 添加子圖
plt.subplot(313)
pass

2、繪圖功能

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

# 一維座標生成
x = np.linspace(0,10,100)

# 二維網格生成
u = np.linspace(-1,1,100)
x,y = np.meshgrid(u,u) 

 座標軸標籤:

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')

 座標軸刻度:

ax.set_xticks([])
ax.set_yticks([])

plt.xticks(range(len(x)), ['a', 'b', 'c', 'd', 'e', 'f'])
plt.yticks(range(1, 8, 2))

 座標網格:

# 橫縱座標單位長度統一
plt.axis('equal')
# 網格
plt.grid(True)

# 網格
ax.grid(True)

 圖表標題:

plt.title('Second Derivative')

 對數座標:

 '''對數座標'''

plt.semilogx(x,y)  # 對x取對數
plt.semilogy(x,y)  # 對y取對數
plt.loglog(x,y)    # 同時取對數

繪圖:

# 色彩填充
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='^')

3、經典實例

餅狀圖

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 t in l_texts:
    t.set_size(20)
# 設置比例數字的字體大小
for t in p_texts:
    t.set_size(20)

plt.show()

 

柱狀圖

import numpy as np
from matplotlib import pyplot as plt

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

n = 12
X = 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()

 

import numpy as np
from matplotlib import pyplot as plt

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

n = 12
X = 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()

 

機率分佈圖

from matplotlib import pyplot as plt
import numpy as np

mu = 0
sigma = 1
x = 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

from matplotlib import pyplot as plt
import numpy as np

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

n = 1024

# 均勻分佈 高斯分佈
# rand 和 randn
X = np.random.rand(1,n)
Y = np.random.rand(1,n)

# 設定顏色
T = 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)

# ref : http://matplotlib.org/examples/pylab_examples/scatter_hist.html

import numpy as np
import matplotlib.pyplot as plt

# the random data
x = np.random.randn(1000)
y = 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()

 

三維數據圖

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

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(9,6),facecolor='white')

# Number of ring
n = 50
size_min = 50
size_max = 50*50

# Ring position
P = np.random.rand(n,2)

# Ring colors R,G,B,A
C = 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
S = 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()

 

美化

# 美化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繪製三維網格(面)

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模式子圖

# 新思路,以前都是生成x和y繪製z=f(x,y)的函數,此次繪製x=f1(z),y=f2(z) z = np.linspace(0, 6, 1000) r = 1 x = r * np.sin(np.pi*2*z) y = r * 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繪製的是三維網格(也就是面)

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()

 

 # 爲等高線圖添加標註

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

 

 

配置Colorbar

# -*- 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也表示藍色。

示例的圖形以下:

相關文章
相關標籤/搜索