python資料視覺化——matplotlib學習筆記

Matplotlib簡介

Matplotlib是Python中一個非常全面可用於建立靜態、動畫和互動式視覺化的庫。

下面是其GitHub倉庫裡面總結的幾張圖,非常好用

Cheatsheets

python資料視覺化——matplotlib學習筆記

Handouts

python資料視覺化——matplotlib學習筆記

使用

基本操作

import matplotlib。pyplot as pltimport numpy as np#基本用法x = np。linspace(-5, 5, 50)y = 2*x + 1# y = x**2plt。plot(x, y)plt。show()

python資料視覺化——matplotlib學習筆記

使用figure 自定義視窗以及在一個圖上畫多條曲線

x = np。linspace(-3, 3, 50)y1 = 2*x + 1y2 = x**2##使用figure 來自定義自己視窗#第一個figure figure下面的圖都在該figure上繪出 直到定義下一個figureplt。figure()plt。plot(x, y1)#第二個figure num是圖片的的索引plt。figure(num=3, figsize=(8, 5),)plt。plot(x, y2)#第一條曲線plt。plot(x, y1, color=‘red’, linewidth=1。0, linestyle=‘——’)#第二條曲線plt。show()

python資料視覺化——matplotlib學習筆記

python資料視覺化——matplotlib學習筆記

設定座標軸

修改座標軸的label

x = np。linspace(-3, 3, 50)y1 = 2*x + 1y2 = x**2plt。figure()plt。plot(x, y2)# plot the second curve in this figure with certain parametersplt。plot(x, y1, color=‘red’, linewidth=1。0, linestyle=‘——’)# set x limits 設定x y的範圍plt。xlim((-1, 2))plt。ylim((-2, 3))plt。xlabel(‘I am x’)# x y 的labelplt。ylabel(‘I am y’)# set new sticks #設定新的刻度new_ticks = np。linspace(-1, 2, 5)print(new_ticks)plt。xticks(new_ticks)# to use ‘$ $’ for math text and nice looking, e。g。 ‘$\pi$’# set tick labels 設定新的label $是為了讓字型更加美觀 |為跳脫字元 可以將alpha轉為數學裡面的αplt。yticks([-2, -1。8, -1, 1。22, 3], [r‘$reallybad$’, r‘$bad\alpha$’, r‘$normal$’, r‘$good$’, r‘$really\ good$’])plt。show()

[-1。 -0。25 0。5 1。25 2。 ]

python資料視覺化——matplotlib學習筆記

修改座標軸的位置

x = np。linspace(-3, 3, 50)y2 = x**2plt。figure(num=3, figsize=(8, 5),)plt。plot(x, y2)#第一條曲線plt。plot(x, y1, color=‘red’, linewidth=1。0, linestyle=‘——’)#第二條曲線# gca = ‘get current axis’ax= plt。gca()ax。spines[‘right’]。set_color(‘none’)# 將上邊和右邊的邊框去掉ax。spines[‘top’]。set_color(‘none’)plt。show()

python資料視覺化——matplotlib學習筆記

x = np。linspace(-3, 3, 50)y2 = x**2plt。figure(num=3, figsize=(8, 5),)plt。plot(x, y2)#第一條曲線plt。plot(x, y1, color=‘red’, linewidth=1。0, linestyle=‘——’)#第二條曲線ax= plt。gca()ax。spines[‘right’]。set_color(‘none’)# 將上邊和右邊的邊框去掉ax。spines[‘top’]。set_color(‘none’)ax。xaxis。set_ticks_position(‘bottom’)# 把下邊的那條變設定為x_axis# ACCEPTS: [ ‘top’ | ‘bottom’ | ‘both’ | ‘default’ | ‘none’ ]ax。spines[‘bottom’]。set_position((‘data’, 0))# 把bottom邊放在y==0的高度# the 1st is in ‘outward’ | ‘axes’ | ‘data’# axes: percentage of y axis# data: depend on y dataax。yaxis。set_ticks_position(‘left’) #把左邊的那條邊設為 y_axis# ACCEPTS: [ ‘left’ | ‘right’ | ‘both’ | ‘default’ | ‘none’ ]ax。spines[‘left’]。set_position((‘data’,0))# 把left 放在x==0的位置plt。show()

python資料視覺化——matplotlib學習筆記

legend 圖例

x = np。linspace(-3, 3, 50)y1 = 2*x + 1y2 = x**2plt。figure()# set x limitsplt。xlim((-1, 2))plt。ylim((-2, 3))# set new sticksnew_sticks = np。linspace(-1, 2, 5)plt。xticks(new_sticks)# set tick labelsplt。yticks([-2, -1。8, -1, 1。22, 3], [r‘$really\ bad$’, r‘$bad$’, r‘$normal$’, r‘$good$’, r‘$really\ good$’])# 設定圖例l1, = plt。plot(x, y1, label=‘linear line’)l2, = plt。plot(x, y2, color=‘red’, linewidth=1。0, linestyle=‘——’, label=‘square line’)#設定圖例的位置plt。legend(loc=‘upper right’) #plt。legend(handles=[l1, l2], labels=[‘up’, ‘down’], loc=‘best’)# the “,” is very important in here l1, = plt。。。 and l2, = plt。。。 for this step“”“legend( handles=(line1, line2, line3), labels=(‘label1’, ‘label2’, ‘label3’), ‘upper right’) The *loc* location codes are:: ‘best’ : 0, (currently not supported for figure legends) ‘upper right’ : 1, ‘upper left’ : 2, ‘lower left’ : 3, ‘lower right’ : 4, ‘right’ : 5, ‘center left’ : 6, ‘center right’ : 7, ‘lower center’ : 8, ‘upper center’ : 9, ‘center’ : 10,”“”plt。show()

python資料視覺化——matplotlib學習筆記

添加註解Annotation

x = np。linspace(-3, 3, 50)y = 2*x + 1plt。figure(num=1, figsize=(8, 5),)plt。plot(x, y,)ax = plt。gca()ax。spines[‘right’]。set_color(‘none’)ax。spines[‘top’]。set_color(‘none’)ax。spines[‘top’]。set_color(‘none’)ax。xaxis。set_ticks_position(‘bottom’)ax。spines[‘bottom’]。set_position((‘data’, 0))ax。yaxis。set_ticks_position(‘left’)ax。spines[‘left’]。set_position((‘data’, 0))x0 = 1y0 = 2*x0 + 1plt。plot([x0, x0,], [0, y0,], ‘k——’, linewidth=2。5)# 畫黑色的虛線 k——表示黑色plt。scatter([x0, ], [y0, ], s=50, color=‘b’)# 畫出該點 b 藍色# method 1:#####################plt。annotate(r‘$2x+1=%s$’ % y0, xy=(x0, y0), xycoords=‘data’, xytext=(+30, -30), textcoords=‘offset points’, fontsize=16, arrowprops=dict(arrowstyle=‘->’, connectionstyle=“arc3,rad=。2”))# method 2:########################plt。text(-3。7, 3, r‘$This\ is\ the\ some\ text。 \mu\ \sigma_i\ \alpha_t$’, fontdict={‘size’: 16, ‘color’: ‘r’})plt。show()

python資料視覺化——matplotlib學習筆記

tick能見度

x = np。linspace(-3, 3, 50)y = 0。1*xplt。figure()plt。plot(x, y, linewidth=10, zorder=1) # set zorder for ordering the plot in plt 2。0。2 or higherplt。ylim(-2, 2)ax = plt。gca() #獲得當前軸ax。spines[‘right’]。set_color(‘none’)ax。spines[‘top’]。set_color(‘none’)ax。xaxis。set_ticks_position(‘bottom’)ax。spines[‘bottom’]。set_position((‘data’, 0))ax。yaxis。set_ticks_position(‘left’)ax。spines[‘left’]。set_position((‘data’, 0))for label in ax。get_xticklabels() + ax。get_yticklabels(): label。set_fontsize(12) # set zorder for ordering the plot in plt 2。0。2 or higher label。set_bbox(dict(facecolor=‘white’, edgecolor=‘none’, alpha=0。8, zorder=2))plt。show()

python資料視覺化——matplotlib學習筆記

Scatter 散點圖

n = 1024 # data sizeX = np。random。normal(0, 1, n)Y = np。random。normal(0, 1, n)T = np。arctan2(Y, X) # for color later onplt。scatter(X, Y, s=75, c=T, alpha=。5)# s為size c為color alpha 為透明度plt。xlim(-1。5, 1。5)plt。xticks(()) # ignore xticksplt。ylim(-1。5, 1。5)plt。yticks(()) # ignore yticks 隱藏所有的ticksplt。show()

python資料視覺化——matplotlib學習筆記

Bar 柱狀圖

n = 12X = np。arange(n)#生成從0-n 12個整數Y1 = (1 - X / float(n)) * np。random。uniform(0。5, 1。0, n)#產生n個0。5-1的數Y2 = (1 - X / float(n)) * np。random。uniform(0。5, 1。0, n)plt。bar(X, +Y1, facecolor=‘#9999ff’, edgecolor=‘white’)plt。bar(X, -Y2, facecolor=‘#ff9999’, edgecolor=‘white’)for x, y in zip(X, Y1): # ha: horizontal alignment # va: vertical alignment plt。text(x + 0。1, y + 0。05, ‘%。2f’ % y, ha=‘center’, va=‘bottom’)for x, y in zip(X, Y2): # ha: horizontal alignment # va: vertical alignment plt。text(x + 0。4, -y - 0。05, ‘%。2f’ % y, ha=‘center’, va=‘top’)plt。xlim(-。5, n)plt。xticks(())plt。ylim(-1。25, 1。25)plt。yticks(())plt。show()

python資料視覺化——matplotlib學習筆記

Contours 等高線圖

def f(x,y): # the height function return (1 - x / 2 + x**5 + y**3) * np。exp(-x**2 -y**2)n = 256x = np。linspace(-3, 3, n)y = np。linspace(-3, 3, n)X,Y = np。meshgrid(x, y)#網格圖# 1。 use plt。contourf to filling contours 填充# X, Y and value for (X,Y) pointplt。contourf(X, Y, f(X, Y), 8, alpha=。75, cmap=plt。cm。hot)# 型別 冷熱圖# 2。 use plt。contour to add contour lines 畫線C = plt。contour(X, Y, f(X, Y), 8, colors=‘black’)#8 代表等高線條數 即等高線的稀疏# 3。 adding labelplt。clabel(C, inline=True, fontsize=10)# inline 為Flase時 label將被線擋住plt。xticks(())plt。yticks(())plt。show()

python資料視覺化——matplotlib學習筆記

image 圖片

# image dataa = np。array([0。313660827978, 0。365348418405, 0。423733120134, 0。365348418405, 0。439599930621, 0。525083754405, 0。423733120134, 0。525083754405, 0。651536351379])。reshape(3,3)“”“for the value of ”interpolation“, check this:http://matplotlib。org/examples/images_contours_and_fields/interpolation_methods。htmlfor the value of ”origin“= [‘upper’, ‘lower’], check this:http://matplotlib。org/examples/pylab_examples/image_origin。html”“”plt。imshow(a, interpolation=‘nearest’, cmap=‘bone’, origin=‘lower’)#plt。colorbar(shrink=。92)# 壓縮為92%plt。xticks(())# 隱藏 ticks plt。yticks(())plt。show()

python資料視覺化——matplotlib學習筆記

3D資料

from mpl_toolkits。mplot3d import Axes3Dfig = plt。figure()# 建一個圖片的視窗ax = Axes3D(fig)# 給視窗新增3D維度# X, Y valueX = np。arange(-4, 4, 0。25)Y = np。arange(-4, 4, 0。25)X, Y = np。meshgrid(X, Y)# 作為網格 R = np。sqrt(X ** 2 + Y ** 2)# height valueZ = np。sin(R)ax。plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt。get_cmap(‘rainbow’))# 1 1分別為行跨 列跨“”“============= ================================================ Argument Description ============= ================================================ *X*, *Y*, *Z* Data values as 2D arrays *rstride* Array row stride (step size), defaults to 10 *cstride* Array column stride (step size), defaults to 10 *color* Color of the surface patches *cmap* A colormap for the surface patches。 *facecolors* Face colors for the individual patches *norm* An instance of Normalize to map values to colors *vmin* Minimum value to map *vmax* Maximum value to map *shade* Whether to shade the facecolors ============= ================================================”“”# I think this is different from plt12_contoursax。contourf(X, Y, Z, zdir=‘z’, offset=-2, cmap=plt。get_cmap(‘rainbow’))“”“========== ================================================ Argument Description ========== ================================================ *X*, *Y*, Data values as numpy。arrays *Z* *zdir* The direction to use: x, y or z (default) *offset* If specified plot a projection of the filled contour on this position in plane normal to zdir ========== ================================================”“”ax。set_zlim(-2, 2)plt。show()

python資料視覺化——matplotlib學習筆記

subplot 多合一顯示

基本方法

# example 1:###############################plt。figure(figsize=(6, 4))# plt。subplot(n_rows, n_cols, plot_num)plt。subplot(2, 2, 1) #兩行兩列 第一張圖plt。plot([0, 1], [0, 1])plt。subplot(222)#也可將逗號省掉 兩行兩列 第二張圖plt。plot([0, 1], [0, 2])plt。subplot(223)#兩行兩列 第三張圖plt。plot([0, 1], [0, 3])plt。subplot(224)#兩行兩列 第四張圖plt。plot([0, 1], [0, 4])plt。tight_layout()

python資料視覺化——matplotlib學習筆記

# example 2:###############################plt。figure(figsize=(6, 4))# plt。subplot(n_rows, n_cols, plot_num)plt。subplot(2, 1, 1)# figure splits into 2 rows, 1 col, plot to the 1st sub-figplt。plot([0, 1], [0, 1])plt。subplot(234)# figure splits into 2 rows, 3 col, plot to the 4th sub-figplt。plot([0, 1], [0, 2])plt。subplot(235)# figure splits into 2 rows, 3 col, plot to the 5th sub-figplt。plot([0, 1], [0, 3])plt。subplot(236)# figure splits into 2 rows, 3 col, plot to the 6th sub-figplt。plot([0, 1], [0, 4])plt。tight_layout()plt。show()

python資料視覺化——matplotlib學習筆記

圖中圖

fig = plt。figure()x = [1, 2, 3, 4, 5, 6, 7]y = [1, 3, 4, 2, 5, 8, 6]# below are all percentageleft, bottom, width, height = 0。1, 0。1, 0。8, 0。8# 小圖相對於figure 的位置大小 (百分比)ax1 = fig。add_axes([left, bottom, width, height]) # main axes 第一個圖ax1。plot(x, y, ‘r’)ax1。set_xlabel(‘x’)ax1。set_ylabel(‘y’)ax1。set_title(‘title’)ax2 = fig。add_axes([0。2, 0。6, 0。25, 0。25]) # inside axes 第二個小圖ax2。plot(y, x, ‘b’)ax2。set_xlabel(‘x’)ax2。set_ylabel(‘y’)ax2。set_title(‘title inside 1’)# different method to add axes####################################plt。axes([0。6, 0。2, 0。25, 0。25])plt。plot(y[::-1], x, ‘g’)plt。xlabel(‘x’)plt。ylabel(‘y’)plt。title(‘title inside 2’)plt。show()

python資料視覺化——matplotlib學習筆記

次座標軸

x = np。arange(0, 10, 0。1)y1 = 0。05 * x**2y2 = -1 *y1fig, ax1 = plt。subplots()ax2 = ax1。twinx() # mirror the ax1 把ax1 的資料映象ax1。plot(x, y1, ‘g-’)ax2。plot(x, y2, ‘b-’)ax1。set_xlabel(‘X data’)ax1。set_ylabel(‘Y1 data’, color=‘g’)ax2。set_ylabel(‘Y2 data’, color=‘b’)plt。show()

python資料視覺化——matplotlib學習筆記

動畫

from matplotlib import animationfig, ax = plt。subplots()x = np。arange(0, 2*np。pi, 0。01)line, = ax。plot(x, np。sin(x))def animate(i): line。set_ydata(np。sin(x + i/10。0)) # update the data return line,# Init only required for blitting to give a clean slate。def init(): line。set_ydata(np。sin(x)) return line,# call the animator。 blit=True means only re-draw the parts that have changed。# blit=True dose not work on Mac, set blit=False# interval= update frequencyani = animation。FuncAnimation(fig=fig, func=animate, frames=100, init_func=init, interval=20, blit=False)# save the animation as an mp4。 This requires ffmpeg or mencoder to be# installed。 The extra_args ensure that the x264 codec is used, so that# the video can be embedded in html5。 You may need to adjust this for# your system: for more information, see# http://matplotlib。sourceforge。net/api/animation_api。html# anim。save(‘basic_animation。mp4’, fps=30, extra_args=[‘-vcodec’, ‘libx264’])plt。show()

python資料視覺化——matplotlib學習筆記