Matplotlib的可以把很多張圖畫到一個顯示界面,在作對比分析的時候非常有用。
常用的三種方式
方式一:通過plt的subplot文章源自四五設計網(wǎng)-http://www.wasochina.com/46603.html
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文章源自四五設計網(wǎng)-http://www.wasochina.com/46603.html
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文章源自四五設計網(wǎng)-http://www.wasochina.com/46603.html
subplots返回的值的類型為元組,其中包含兩個元素:第一個為一個畫布,第二個是子圖文章源自四五設計網(wǎng)-http://www.wasochina.com/46603.html
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()
運行結果如下文章源自四五設計網(wǎng)-http://www.wasochina.com/46603.html
文章源自四五設計網(wǎng)-http://www.wasochina.com/46603.html
就是這么簡單,文章源自四五設計網(wǎng)-http://www.wasochina.com/46603.html
如何不規(guī)則劃分
前面的兩個圖占了221和222的位置,如果想在下面只放一個圖,得把前兩個當成一列,即2行1列第2個位置文章源自四五設計網(wǎng)-http://www.wasochina.com/46603.html
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()
運行結果如下文章源自四五設計網(wǎng)-http://www.wasochina.com/46603.html
文章源自四五設計網(wǎng)-http://www.wasochina.com/46603.html
到此這篇關于Matplotlib繪制子圖的常見幾種方法的文章就介紹到這了


評論