Matplotlib - 簡單繪圖



在本章中,我們將學習如何使用 Matplotlib 建立一個簡單的繪圖。

現在我們將使用 Matplotlib 顯示一個簡單的線形圖,該圖顯示弧度角與其正弦值的關係。首先,根據約定,我們從 Matplotlib 包中匯入 Pyplot 模組,並使用別名 plt。

import matplotlib.pyplot as plt

接下來,我們需要一個要繪製的數字陣列。NumPy 庫中定義了各種陣列函式,該庫使用別名 np 匯入。

import numpy as np

現在,我們使用 NumPy 庫中的 arange() 函式獲取 0 到 2π 之間角度的 ndarray 物件。

x = np.arange(0, math.pi*2, 0.05)

ndarray 物件用作圖形的 x 軸上的值。對應於 x 中角度的正弦值將顯示在 y 軸上,透過以下語句獲取:-

y = np.sin(x)

使用 plot() 函式繪製來自兩個陣列的值。

plt.plot(x,y)

您可以設定繪圖示題以及 x 和 y 軸的標籤。

You can set the plot title, and labels for x and y axes.
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')

透過 show() 函式呼叫繪圖檢視器視窗:-

plt.show()

完整的程式如下:-

from matplotlib import pyplot as plt
import numpy as np
import math #needed for definition of pi
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
plt.plot(x,y)
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')
plt.show()

執行上述程式碼行時,將顯示以下圖形:-

Simple Plot

現在,在 Jupyter notebook 中使用 Matplotlib。

如前所述,從 Anaconda navigator 或命令列啟動 Jupyter notebook。在輸入單元格中,輸入 Pyplot 和 NumPy 的匯入語句:-

from matplotlib import pyplot as plt
import numpy as np

為了在筆記本本身(而不是在單獨的檢視器中)顯示繪圖輸出,請輸入以下魔法語句:-

%matplotlib inline

獲取 x 作為包含 0 到 2π 之間弧度角的 ndarray 物件,以及每個角度的正弦值 y:-

import math
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)

設定 x 和 y 軸的標籤以及繪圖示題:-

plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')

最後,執行 plot() 函式以在筆記本中生成正弦波顯示(無需執行 show() 函式):-

plt.plot(x,y)

執行最後一行程式碼後,將顯示以下輸出:-

Final Line of Code
廣告