Matplotlib如何繪製子圖

前言

Matplotlib的能夠把不少張圖畫到一個顯示界面,在做對比分析的時候很是有用。
對應的有plt的subplot和figure的add_subplo的方法,參數能夠是一個三位數字(例如111),也能夠是一個數組(例如[1,1,1]),3個數字分別表明api

  1. 子圖總行數
  2. 子圖總列數
  3. 子圖位置

更多詳情能夠查看:matplotlib文檔數組

下面貼出兩種繪子圖的代碼dom

經常使用的兩種方式

方式一:經過plt的subplot

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# author: chenqionghe

# 畫第1個圖:折線圖
x=np.arange(1,100)
plt.subplot(221)
plt.plot(x,x*x)

# 畫第2個圖:散點圖
plt.subplot(222)
plt.scatter(np.arange(0,10), np.random.rand(10))

# 畫第3個圖:餅圖
plt.subplot(223)
plt.pie(x=[15,30,45,10],labels=list('ABCD'),autopct='%.0f',explode=[0,0.05,0,0])

# 畫第4個圖:條形圖
plt.subplot(224)
plt.bar([20,10,30,25,15],[25,15,35,30,20],color='b')
plt.show()

方式二:經過figure的add_subplot

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# author: chenqionghe

fig=plt.figure()

# 畫第1個圖:折線圖
x=np.arange(1,100)
ax1=fig.add_subplot(221)
ax1.plot(x,x*x)

# 畫第2個圖:散點圖
ax2=fig.add_subplot(222)
ax2.scatter(np.arange(0,10), np.random.rand(10))

# 畫第3個圖:餅圖
ax3=fig.add_subplot(223)
ax3.pie(x=[15,30,45,10],labels=list('ABCD'),autopct='%.0f',explode=[0,0.05,0,0])

# 畫第4個圖:條形圖
ax4=fig.add_subplot(224)
ax4.bar([20,10,30,25,15],[25,15,35,30,20],color='b')
plt.show()

方式三:經過plt的subplots

subplots返回的值的類型爲元組,其中包含兩個元素:第一個爲一個畫布,第二個是子圖code

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# author: chenqionghe

fig,subs=plt.subplots(2,2)

# 畫第1個圖:折線圖
x=np.arange(1,100)
subs[0][0].plot(x,x*x)

# 畫第2個圖:散點圖
subs[0][1].scatter(np.arange(0,10), np.random.rand(10))

# 畫第3個圖:餅圖
subs[1][0].pie(x=[15,30,45,10],labels=list('ABCD'),autopct='%.0f',explode=[0,0.05,0,0])

# 畫第4個圖:條形圖
subs[1][1].bar([20,10,30,25,15],[25,15,35,30,20],color='b')
plt.show()

運行結果以下
htm

就是這麼簡單,blog

如何不規則劃分

前面的兩個圖佔了221和222的位置,若是想在下面只放一個圖,得把前兩個當成一列,即2行1列第2個位置文檔

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# author: chenqionghe

# 畫第1個圖:折線圖
x=np.arange(1,100)
plt.subplot(221)
plt.plot(x,x*x)

# 畫第2個圖:散點圖
plt.subplot(222)
plt.scatter(np.arange(0,10), np.random.rand(10))

# 畫第3個圖:餅圖
plt.subplot(223)
plt.pie(x=[15,30,45,10],labels=list('ABCD'),autopct='%.0f',explode=[0,0.05,0,0])

# 畫第3個圖:條形圖
# 前面的兩個圖佔了221和222的位置,若是想在下面只放一個圖,得把前兩個當成一列,即2行1列第2個位置
plt.subplot(212)
plt.bar([20,10,30,25,15],[25,15,35,30,20],color='b')
plt.show()

運行結果以下
get

沒錯,就是這麼簡單!pandas