Matplotlib 子圖的創建


在matplotlib中,整個圖像為一個Figure對象

在Figure對象中可以包含一個或者多個Axes對象  每個Axes對象相當於一個子圖了

每個Axes(ax)對象都是一個擁有自己坐標系統的繪圖區域

plt.figure, plt.subplot

1.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
% matplotlib inline
# 導入相關模塊

# 子圖創建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='.')
# 也可以直接在子圖后用圖表創建函數直接生成圖表

輸出:

[<matplotlib.lines.Line2D at 0x1d078fe2e48>,
 <matplotlib.lines.Line2D at 0x1d078fea2e8>,
 <matplotlib.lines.Line2D at 0x1d078fea4e0>,
 <matplotlib.lines.Line2D at 0x1d078fea668>]

 

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

fig,axes = plt.subplots(2,3,figsize=(10,4))   #因為這里返回兩個對象,一個使整體圖表的對象,一個是不同子圖組成的數組
print(fig)
print(axes, axes.shape, type(axes))
ts = pd.Series(np.random.randn(1000).cumsum())

# 生成圖表對象的數組

ax1 = axes[0,1]   #指定了第0排第一個圖表
ax1.plot(ts)

df = pd.DataFrame(np.random.rand(100,2))
df.plot()
df.plot(ax = axes[1,0])

輸出:

Figure(720x288)
[[<matplotlib.axes._subplots.AxesSubplot object at 0x0000026A4E8A2668>
  <matplotlib.axes._subplots.AxesSubplot object at 0x0000026A4E620A90>
  <matplotlib.axes._subplots.AxesSubplot object at 0x0000026A4E039358>]
 [<matplotlib.axes._subplots.AxesSubplot object at 0x0000026A4DFB31D0>
  <matplotlib.axes._subplots.AxesSubplot object at 0x0000026A4E4BFCC0>
  <matplotlib.axes._subplots.AxesSubplot object at 0x0000026A4E0F7710>]] (2, 3) <class 'numpy.ndarray'>
<matplotlib.axes._subplots.AxesSubplot at 0x26a4dfb31d0>

3.

# plt.subplots,參數調整

fig,axes = plt.subplots(2,2,sharex=True,sharey=True)
# sharex,sharey:是否共享x,y刻度     所有subplot之間應該使用相同的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.5,hspace=0.5)
# wspace,hspace:用於控制子圖之間的水平間隔和垂直間隔

輸出:

 

 

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM