Python圖表繪製工具:Matplotlib_Part 1

###序言:     Python的可視化工具,如下截圖,均以展現圖表實例,如需瞭解部分對象的輸出結果,可參照我Github上的代碼,3Q🌹python


####【課程3.1】 Matplotlib簡介及圖表窗口     Matplotlib → 一個python版的matlab繪圖接口,以2D爲主,支持python、numpy、pandas基本數據結構,運營高效且有較豐富的圖表庫git

圖表窗口1 → plt.show()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# 圖表窗口1 → plt.show()

plt.plot(np.random.rand(10))
plt.show()
# 直接生成圖表
複製代碼

1.png


圖表窗口2 → 魔法函數,嵌入圖表
# 圖表窗口2 → 魔法函數,嵌入圖表

% matplotlib inline  
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.scatter(x,y)
# 直接嵌入圖表,不用plt.show()
# <matplotlib.collections.PathCollection at ...> 表明該圖表對象
複製代碼

2.png


>##### 圖表窗口3 → 魔法函數,彈出可交互的matplotlib窗口 ``` # 圖表窗口3 → 魔法函數,彈出可交互的matplotlib窗口

% matplotlib notebook s = pd.Series(np.random.randn(100)) s.plot(style = 'k--o',figsize=(10,5))github

可交互的matplotlib窗口,不用plt.show()

可作必定調整

![3.png](https://upload-images.jianshu.io/upload_images/2330091-4bc58a4f1bdacb44.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

<br>
>##### 圖表窗口4 → 魔法函數,彈出matplotlib控制檯
複製代碼

圖表窗口4 → 魔法函數,彈出matplotlib控制檯

% matplotlib qt5 df = pd.DataFrame(np.random.rand(50,2),columns=['A','B']) df.hist(figsize=(12,5),color='g',alpha=0.8)spring

可交互性控制檯

若是已經設置了顯示方式(好比notebook),須要重啓而後再運行魔法函數

網頁嵌入的交互性窗口 和 控制檯,只能顯示一個

#plt.close()數組

關閉窗口

#plt.gcf().clear()bash

每次清空圖表內內容

PS:這裏須要用代碼調試
<br>

####【課程3.2】 圖表的基本元素
&ensp;&ensp;&ensp;&ensp;圖表內基本參數設置

>##### 圖名,圖例,軸標籤,軸邊界,軸刻度,軸刻度標籤等
複製代碼

圖名,圖例,軸標籤,軸邊界,軸刻度,軸刻度標籤等

df = pd.DataFrame(np.random.rand(10,2),columns=['A','B']) fig = df.plot(figsize=(6,4))數據結構

figsize:建立圖表窗口,設置窗口大小

建立圖表對象,並賦值與fig

plt.title('Interesting Graph - Check it out') # 圖名 plt.xlabel('Plot Number') # x軸標籤 plt.ylabel('Important var') # y軸標籤dom

plt.legend(loc = 'upper right')svg

顯示圖例,loc表示位置

'best' : 0, (only implemented for axes 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.xlim([0,12]) # x軸邊界 plt.ylim([0,1.5]) # y軸邊界 plt.xticks(range(10)) # 設置x刻度 plt.yticks([0,0.2,0.4,0.6,0.8,1.0,1.2]) # 設置y刻度 fig.set_xticklabels("%.1f" %i for i in range(10)) # x軸刻度標籤 fig.set_yticklabels("%.2f" %i for i in [0,0.2,0.4,0.6,0.8,1.0,1.2]) # y軸刻度標籤函數

範圍只限定圖表的長度,刻度則是決定顯示的標尺 → 這裏x軸範圍是0-12,但刻度只是0-9,刻度標籤使得其顯示1位小數

軸標籤則是顯示刻度的標籤

print(fig,type(fig))

查看錶格自己的顯示方式,以及類別

![4.png](https://upload-images.jianshu.io/upload_images/2330091-2a380146238d0e50.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


<br>
>##### 其餘元素可視性
複製代碼

其餘元素可視性

x = np.linspace(-np.pi,np.pi,256,endpoint = True) c, s = np.cos(x), np.sin(x) plt.plot(x, c) plt.plot(x, s)

經過ndarry建立圖表

plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'x')

顯示網格

linestyle:線型

color:顏色

linewidth:寬度

axis:x,y,both,顯示x/y/二者的格網

plt.tick_params(bottom='on',top='off',left='on',right='off')

刻度顯示

import matplotlib matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'inout'

設置刻度的方向,in,out,inout

這裏須要導入matploltib,而不單單導入matplotlib.pyplot

frame = plt.gca() #plt.axis('off')

關閉座標軸

#frame.axes.get_xaxis().set_visible(False) #frame.axes.get_yaxis().set_visible(False)

x/y 軸不可見

![5.png](https://upload-images.jianshu.io/upload_images/2330091-e57a97557b67e799.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


<br>

####【課程3.3】 圖表的樣式參數
&ensp;&ensp;&ensp;&ensp;linestyle、style、color、marker
>##### linestyle參數
複製代碼

linestyle參數

plt.plot([i**2 for i in range(100)], linestyle = '-.')

'-' solid line style

'--' dashed line style

'-.' dash-dot line style

':' dotted line style

![6.png](https://upload-images.jianshu.io/upload_images/2330091-e3dfcd9220e0a0e9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


<br>
>##### marker參數
複製代碼

marker參數

s = pd.Series(np.random.randn(100).cumsum()) s.plot(linestyle = '--', marker = '.')

'.' point marker

',' pixel marker

'o' circle marker

'v' triangle_down marker

'^' triangle_up marker

'<' triangle_left marker

'>' triangle_right marker

'1' tri_down marker

'2' tri_up marker

'3' tri_left marker

'4' tri_right marker

's' square marker

'p' pentagon marker

'*' star marker

'h' hexagon1 marker

'H' hexagon2 marker

'+' plus marker

'x' x marker

'D' diamond marker

'd' thin_diamond marker

'|' vline marker

'_' hline marker

![7.png](https://upload-images.jianshu.io/upload_images/2330091-15c0e5e82532d4c7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


<br>
>##### color參數
複製代碼

color參數

plt.hist(np.random.randn(100), color = 'g',alpha = 0.8)

alpha:0-1,透明度

經常使用顏色簡寫:red-r, green-g, black-k, blue-b, yellow-y

df = pd.DataFrame(np.random.randn(1000, 4),columns=list('ABCD')) df = df.cumsum() df.plot(style = '--.',alpha = 0.8,colormap = 'GnBu')

colormap:顏色板,包括:

Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r,

Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r,

PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r,

RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r,

YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r,

cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r,

gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot,

gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral,

nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spectral,

spectral_r ,spring, spring_r, summer, summer_r, terrain, terrain_r, viridis, viridis_r, winter, winter_r

其餘參數見「顏色參數.docx」

![8.png](https://upload-images.jianshu.io/upload_images/2330091-3ecd60c25321be36.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


<br>
>##### style參數,能夠包含linestyle,marker,color
複製代碼

style參數,能夠包含linestyle,marker,color

ts = pd.Series(np.random.randn(1000).cumsum(), index=pd.date_range('1/1/2000', periods=1000)) ts.plot(style = '--g.',grid = True)

style → 風格字符串,這裏包括了linestyle(-),marker(.),color(g)

plot()內也有grid參數

![9.png](https://upload-images.jianshu.io/upload_images/2330091-52b6af5af44a41c9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


<br>
>##### 總體風格樣式
複製代碼

總體風格樣式

import matplotlib.style as psl print(plt.style.available)

查看樣式列表

psl.use('ggplot') ts = pd.Series(np.random.randn(1000).cumsum(), index=pd.date_range('1/1/2000', periods=1000)) ts.plot(style = '--g.',grid = True,figsize=(10,6))

一旦選用樣式後,全部圖表都會有樣式,重啓後才能關掉

![10.png](https://upload-images.jianshu.io/upload_images/2330091-93f5897fb0213ef6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


<br>

####【課程3.4】 刻度、註解、圖表輸出
&ensp;&ensp;&ensp;&ensp;主刻度、次刻度
>##### 刻度
複製代碼

刻度

from matplotlib.ticker import MultipleLocator, FormatStrFormatter

t = np.arange(0.0, 100.0, 1) s = np.sin(0.1np.pit)np.exp(-t0.01) ax = plt.subplot(111) #注意:通常都在ax中設置,再也不plot中設置 plt.plot(t,s,'--*') plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'both')

網格

#plt.legend() # 圖例

xmajorLocator = MultipleLocator(10) # 將x主刻度標籤設置爲10的倍數 xmajorFormatter = FormatStrFormatter('%.0f') # 設置x軸標籤文本的格式 xminorLocator = MultipleLocator(5) # 將x軸次刻度標籤設置爲5的倍數
ymajorLocator = MultipleLocator(0.5) # 將y軸主刻度標籤設置爲0.5的倍數 ymajorFormatter = FormatStrFormatter('%.1f') # 設置y軸標籤文本的格式 yminorLocator = MultipleLocator(0.1) # 將此y軸次刻度標籤設置爲0.1的倍數

ax.xaxis.set_major_locator(xmajorLocator) # 設置x軸主刻度 ax.xaxis.set_major_formatter(xmajorFormatter) # 設置x軸標籤文本格式 ax.xaxis.set_minor_locator(xminorLocator) # 設置x軸次刻度

ax.yaxis.set_major_locator(ymajorLocator) # 設置y軸主刻度 ax.yaxis.set_major_formatter(ymajorFormatter) # 設置y軸標籤文本格式 ax.yaxis.set_minor_locator(yminorLocator) # 設置y軸次刻度

ax.xaxis.grid(True, which='both') #x座標軸的網格使用主刻度 ax.yaxis.grid(True, which='minor') #y座標軸的網格使用次刻度

which:格網顯示

#刪除座標軸的刻度顯示 #ax.yaxis.set_major_locator(plt.NullLocator()) #ax.xaxis.set_major_formatter(plt.NullFormatter())

![11.png](https://upload-images.jianshu.io/upload_images/2330091-5b683cb30548fbcf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


<br>
>##### 註解
複製代碼

註解

df = pd.DataFrame(np.random.randn(10,2)) df.plot(style = '--o') plt.text(5,0.5,'hahaha',fontsize=10)

註解 → 橫座標,縱座標,註解字符串

![12.png](https://upload-images.jianshu.io/upload_images/2330091-ec7908d102b08eb4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


<br>
>#####圖表輸出
複製代碼

圖表輸出

df = pd.DataFrame(np.random.randn(1000, 4), columns=list('ABCD')) df = df.cumsum() df.plot(style = '--.',alpha = 0.5) plt.legend(loc = 'upper left') plt.savefig('C:/Users/Hjx/Desktop/pic.png', dpi=400, bbox_inches = 'tight', facecolor = 'g', edgecolor = 'b')

可支持png,pdf,svg,ps,eps…等,之後綴名來指定

dpi是分辨率

bbox_inches:圖表須要保存的部分。若是設置爲‘tight’,則嘗試剪除圖表周圍的空白部分。

facecolor,edgecolor: 圖像的背景色,默認爲‘w’(白色)

![13.png](https://upload-images.jianshu.io/upload_images/2330091-5163f2d3ed71d5f7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


<br>

####【課程3.5】 子圖
&ensp;&ensp;&ensp;&ensp;在matplotlib中,整個圖像爲一個Figure對象
在Figure對象中能夠包含一個或者多個Axes對象
每一個Axes(ax)對象都是一個擁有本身座標系統的繪圖區域
&ensp;&ensp;&ensp;&ensp;plt.figure, plt.subplot
>##### plt.figure() 繪圖對象
複製代碼

plt.figure() 繪圖對象

plt.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None,

frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, **kwargs)

fig1 = plt.figure(num=1,figsize=(4,2)) plt.plot(np.random.rand(50).cumsum(),'k--') fig2 = plt.figure(num=2,figsize=(4,2)) plt.plot(50-np.random.rand(50).cumsum(),'k--')

num:圖表序號,能夠試試不寫或都爲同一個數字的狀況,圖表如何顯示

figsize:圖表大小

當咱們調用plot時,若是設置plt.figure(),則會自動調用figure()生成一個figure, 嚴格的講,是生成subplots(111)

![14.png](https://upload-images.jianshu.io/upload_images/2330091-9cb8e76e6490833a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


<br>
>##### 子圖建立1 - 先創建子圖而後填充圖表
複製代碼

子圖建立1 - 先創建子圖而後填充圖表

fig = plt.figure(figsize=(10,6),facecolor = 'gray')

ax1 = fig.add_subplot(2,2,1) # 第一行的左圖 plt.plot(np.random.rand(50).cumsum(),'k--') plt.plot(np.random.randn(50).cumsum(),'b--')

先建立圖表figure,而後生成子圖,(2,2,1)表明建立2*2的矩陣表格,而後選擇第一個,順序是從左到右從上到下

建立子圖後繪製圖表,會繪製到最後一個子圖

ax2 = fig.add_subplot(2,2,2) # 第一行的右圖 ax2.hist(np.random.rand(50),alpha=0.5)

ax4 = fig.add_subplot(2,2,4) # 第二行的右圖 df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd']) ax4.plot(df2,alpha=0.5,linestyle='--',marker='.')

也能夠直接在子圖後用圖表建立函數直接生成圖表

![15.png](https://upload-images.jianshu.io/upload_images/2330091-effd8c5af1a6ad84.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


<br>
>##### 子圖建立2 - 建立一個新的figure,並返回一個subplot對象的numpy數組 → plt.subplot
複製代碼

子圖建立2 - 建立一個新的figure,並返回一個subplot對象的numpy數組 → plt.subplot

fig,axes = plt.subplots(2,3,figsize=(10,4)) ts = pd.Series(np.random.randn(1000).cumsum()) print(axes, axes.shape, type(axes))

生成圖表對象的數組

ax1 = axes[0,1] ax1.plot(ts)

![16.png](https://upload-images.jianshu.io/upload_images/2330091-0810c5bc9b8ea406.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


<br>
>#####plt.subplots,參數調整
複製代碼

plt.subplots,參數調整

fig,axes = plt.subplots(2,2,sharex=True,sharey=True)

sharex,sharey:是否共享x,y刻度

for i in range(2): for j in range(2): axes[i,j].hist(np.random.randn(500),color='k',alpha=0.5) plt.subplots_adjust(wspace=0,hspace=0)

wspace,hspace:用於控制寬度和高度的百分比,好比subplot之間的間距

![17.png](https://upload-images.jianshu.io/upload_images/2330091-5f21e64bebd8fa15.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


<br>
>##### 子圖建立3 - 多系列圖,分別繪製
複製代碼

子圖建立3 - 多系列圖,分別繪製

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD')) df = df.cumsum() df.plot(style = '--.',alpha = 0.4,grid = True,figsize = (8,8), subplots = True, layout = (2,3), sharex = False) plt.subplots_adjust(wspace=0,hspace=0.2)

plt.plot()基本圖表繪製函數 → subplots,是否分別繪製系列(子圖)

layout:繪製子圖矩陣,按順序填充

![18.png](https://upload-images.jianshu.io/upload_images/2330091-970e573c768c2138.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)



<br>

#####最後:
[以上完整代碼](https://github.com/ChaoRenYuan/Python/tree/master/Python數據分析工具/圖表繪製工具:Matplotlib)
複製代碼
相關文章
相關標籤/搜索