subplots()使用方法舉例說明

plt.subplots()

plt.subplots() 和 plt.subplot() 功能作用非常相似。
matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)
部分參數介紹:
nrows, ncols : int, optional, default: 1
Number of rows/columns of the subplot grid.
可以手動輸出幾行幾列,默認是1行1列
sharex, sharey : bool or {‘none’, ‘all’, ‘row’, ‘col’}, default: False
可以選擇共享x軸或者y軸:

  1. True or ‘all’: x- or y-axis will be shared among all subplots.
  2. False or ‘none’: each subplot x- or y-axis will be independent.
  3. ‘row’: each subplot row will share an x- or y-axis.
  4. ‘col’: each subplot column will share an x- or y-axis.
    num : integer or string, optional, default: None
    A pyplot.figure keyword that sets the figure number or label.選擇生成幾個figure

demo

import matplotlib.pyplot as plt
import numpy as np

#First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

#Creates just a figure and only one subplot
fig, ax = plt.subplots() # 創建一個子圖
ax.plot(x, y)
ax.set_title('Simple plot')

plt.show() # 圖1

#Creates two subplots and unpacks the output array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)

plt.show() # 圖2

#Creates four polar axes, and accesses them through the returned array
fig, axes = plt.subplots(2, 2, subplot_kw=dict(polar=True))
axes[0, 0].plot(x, y)
axes[1, 1].scatter(x, y)

plt.show() # 圖3

#Share a X axis with each column of subplots 共享各個軸
plt.subplots(2, 2, sharex='col')

#Share a Y axis with each row of subplots
plt.subplots(2, 2, sharey='row')

#Share both X and Y axes with all subplots
plt.subplots(2, 2, sharex='all', sharey='all')

#Note that this is the same as
plt.subplots(2, 2, sharex=True, sharey=True)

#Creates figure number 10 with a single subplot
#and clears it if it already exists.
#fig, ax=plt.subplots(num=10, clear=True)
#plt.show()

生成圖像如下:
圖1
在這裏插入圖片描述
圖2
在這裏插入圖片描述
圖3
在這裏插入圖片描述

可以看到,plt.subplots()的功能還是非常強大的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章