如何在 Python 中繪製使用 def 定義的函式? (Matplotlib)


要在 Python 中繪製使用 def 定義的函式,我們可以採取以下步驟 −

  • 設定圖形大小並調整子圖之間和周圍的填充
  • 使用 def,即可 f(x) 建立使用者自定義函式。
  • 使用 numpy 建立 x 資料點。
  • 使用 plot() 方法繪製 xf(x)
  • 要顯示圖形,請使用 show() 方法。

示例

import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

def f(x):
   return np.sin(x) + x + x * np.sin(x)

x = np.linspace(-10, 10, 100)

plt.plot(x, f(x), color='red')

plt.show()

輸出

更新日期:2023 年 8 月 24 日

66K+ 瀏覽次數

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.