使用 Matplotlib 繪製 2D 和 3D 圖形

1. 繪製2D圖像

注意:如果在NoteBook環境下繪圖時應該首先運行%matplotlib inline

1.1. 與MATLAB相似的用法

from matplotlib import pylab
import numpy as np
%matplotlib inline

x = np.linspace(0, 10, 20)				#構造數據
y = x * x + 2

pylab.subplot(1,2,1)		#繪製子圖1,並指定以下語句是在此子圖上繪製
pylab.plot(y,x,'g*-')			#這裏的'g*-'是線條的屬性設置,和MATLAB一致

pylab.subplot(1,2,2)		#子圖2,以下繪製在子圖2中
pylab.plot(y,x,'r--')

在這裏插入圖片描述

1.2. 面向對象的方法

from matplotlib import pyplot as plt
import numpy as np
%matplotlib inline

x = np.linspace(0, 10, 20)				#構造數據
y = x * x + 2

#------------------------------------方法 1:add_axes方法添加畫布--------------------------

fig = plt.figure() # 新建圖形對象,畫板,圖像的框架,可以通過 figsize=(14,6)指定畫板尺寸

#add_axes參數的前兩個表示座標,後兩個表示圖像長和高,範圍[0,1] 
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) 	#創建畫布,即子圖,此方法創建的子圖可以重疊

#創建子圖2
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3])

axes1.plot(x, y, 'r')
axes2.plot(y, x, 'g')

#------------------------------------方法三:使用 subplots() 添加畫布--------------------------
#fig爲畫板對象,axes爲畫布對象列表
fig, axes = plt.subplots(nrows=1, ncols=2) # 子圖爲 1 行,2 列,參數可以直接寫爲(1,2)
for ax in axes:
    ax.plot(x, y, 'r')

#------------------------------------方法三:使用 add_subplot() 添加畫布--------------------------
#													'''此方法與MATLAB方法相似'''

fig = plt.figure() 		# 新建圖形對象

fig.add_subplot(1,2,1)

plt.plot(x, y, 'r')
fig.add_subplot(1,2,2)

plt.plot(x, y, 'g')

方法一:
方法一
方法二:
在這裏插入圖片描述
方法三:
在這裏插入圖片描述

1.3. 圖的屬性設置

  1. 圖名稱、座標軸名稱、圖例
#1.設置標題
ax.set_title("title")

#2.設置座標軸名稱
ax.set_xlabel("x")
ax.set_ylabel("y")

#3. 設置圖例,其中loc 參數標記圖例位置1,2,3,4 
#依次代表:右上角、左上角、左下角,右下角;0 代表自適應
ax.legend(["label1", "label2"],loc=0)

  1. 畫布網格、座標軸範圍
    使用畫布方法
axes.grid(True)	#設置網格,默認爲False

#設置座標軸範圍
axes.set_ylim([0, 60])
axes.set_xlim([2, 5])

  1. 線型、顏色、透明度、虛線交錯寬度

    1. 方法一:
      顏色、線型、標記由三種符號組成:如 ‘r–^’ :紅色、虛線、朝上三角標記。然後在指定其他參數
    ax.plot(x, x+1,  'r--^', lw=1)
    
    1. 方法二:
      全部由關鍵字傳參
    ax.plot(x, x+16, color="purple", lw=1, ls='-', marker='s', markersize=8, 
        markerfacecolor="yellow", markeredgewidth=2, markeredgecolor="blue")
    
    1. plot()參數
    參數 描述
    color 顏色
    alpha 透明度
    linestyle ,ls 線型
    linewidth ,lw 線寬
    marker 線標記
    markersize,ms 標記大小
    markeredgewidth mew 標記邊界寬度
    markerfacecolor ,mfc 標記內部顏色
    markeredgecolor, mec 標記邊界顏色
    1. 線型:
    描述
    -’ 實線
    ‘–’ 線型虛線
    ‘-.’ 點劃線 點線交錯
    ‘:’ 點型虛線

    注意:虛線交錯寬度設置

    line, = ax.plot(x, x+8, color="black", lw=1.50)
    line.set_dashes([5, 10, 15, 10]) #偶數個列表,每兩個樹爲一個實線與虛線的交錯寬度
    
    1. 線標記:
    符號 描述
    ‘.’ 點標記
    ‘,’ 像素標記
    ‘o’ 圓圈標記
    ‘v’ 朝下的三角形
    ‘^’ 朝上的三角形
    ‘<’ 朝左的三角形
    ‘>’ 朝右的三角形
    1-4 tri_down marker,up,left,right
    ‘s’ 正方形
    ‘p’ 五邊形
    ‘*’ 星型
    ‘h’ 1號六角形
    ‘H’ 2號六角形
    ‘+’ +號標記
    ‘x’ x號標記
    ‘D’ 鑽石形
    ‘d’ 小版鑽石形
    ‘|’ 垂直線形
    ‘_’ 水平線行
    1. 顏色
    符號 描述
    ‘b’ 藍色
    ‘g’ 綠色
    ‘r’ 紅色
    ‘c’ 青色
    ‘m’ 品紅
    ‘y’ 黃色
    ‘k’ 黑色
    ‘w’ 白色

    其中顏色可以由完整的英文名稱、十六進制字符碼(’#777777’)、RGB、RGBA元組(((0, 128, 64))),只有符號表示的可以用方法一格式化組合線的屬性,其他需用關鍵字傳參。

1.4. 其他二維圖

  1. 繪製散點圖、梯步圖、條形圖、面積圖
"""繪製散點圖、梯步圖、條形圖、面積圖
"""
n = np.array([0,1,2,3,4,5])

fig, axes = plt.subplots(1, 4, figsize=(16,5))

axes[0].scatter(x, x + 0.25*np.random.randn(len(x)))
axes[0].set_title("scatter")

axes[1].step(n, n**2, lw=2)
axes[1].set_title("step")

axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)
axes[2].set_title("bar")

# 提供兩個函數,繪製交叉面積
axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5)
axes[3].set_title("fill_between")

在這裏插入圖片描述
2. 繪製直方圖和累計直方圖

"""繪製直方圖
"""
n = np.random.randn(100000)
fig, axes = plt.subplots(1, 2, figsize=(12,4))

axes[0].hist(n)
axes[0].set_title("Default histogram")
axes[0].set_xlim((min(n), max(n)))

axes[1].hist(n, cumulative=True, bins=50)
axes[1].set_title("Cumulative detailed histogram")
axes[1].set_xlim((min(n), max(n)))

在這裏插入圖片描述

2. 繪製3D圖

2.1. 在三維空間中繪製散點

from mpl_toolkits.mplot3d.axes3d import Axes3D

fig = plt.figure(figsize=(14,6))

# 通過 projection='3d' 指定繪製 3D 圖形
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.scatter([1,2,3], [1,2,3], [1,2,3],c='r')			#分別對應三個座標xyz,可以爲單個數字表示單個座標,可以爲三個列表,表示多個座標

2.2. 在三維空間中繪製連續圖形

注意事項:

  1. 需要關聯XY
    np.meshgrid(phi_p, phi_m)的作用是用對應的輸入生成二維空間中的點。
from mpl_toolkits.mplot3d.axes3d import Axes3D

#數據生成
phi_m = np.linspace(0, 2*np.pi, 100)
phi_p = np.linspace(0, 2*np.pi, 100)
X,Y = np.meshgrid(phi_p, phi_m)
Z = flux_qubit_potential(X, Y).T

fig = plt.figure(figsize=(14,6))

# 通過 projection='3d' 指定繪製 3D 圖形
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0)

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