Matplotlib資料視覺化——subplot的另外三種常用方法
阿新 • • 發佈:2018-12-22
第一種方法:subplot2grid
定義一個3*3的矩陣位置,利用subplot2grid分別框選出想要的區域大小,進而在區域中plot出想繪製的函式即可,colspan與rowspan分別表示行數和列數,用來界定大小
說明:
通過這種方法設定title和label需要在前面加上set_
import matplotlib.pyplot as plt
# 第一種方法
plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)
ax1.plot([1, 2], [1, 2])
ax1.set_title( 'x title')
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2,)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))
plt.show()
第二種方法:subplot2grid
藉助matplotlib中的gridspec方法進行劃分區域
import matplotlib.pyplot as plt
import matplotlib. gridspec as gridspec
# 第二種方法
plt.figure()
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :]) # 第一行的全部位置
ax2 = plt.subplot(gs[1, :2])# 第二行前兩個位置
ax3 = plt.subplot(gs[1:, 2])# 第三行到最後一行,第三個位置
ax4 = plt.subplot(gs[-1, 0])# 最後一行第一個位置
ax5 = plt.subplot(gs[-1, -2])# 最後一行倒數第二個位置
plt.show()
第二種方法:subplots
藉助subplots返回兩個物件,一個是figure的資訊,一個是位置資訊。
import matplotlib.pyplot as plt
# 第三種方法
f, ((ax11, ax12), (ax21, ax22))= plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1, 2], [1, 2])
ax12.plot([1, 2], [1, 2])
plt.show()
大家選一個去繪製即可,最後的結果是一樣的