Python 繪製三角函數圖形

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。

問題:「如何使用Python來繪製三角函數圖形呢?」

OK,在繪製圖形前,先來了解 Python 的數學程式庫(Mathematical functions)有哪些,從3.6.2的文件可看到如下:
math.cos(x)
Return the cosine of x radians.
math.sin(x)
Return the sine of x radians.
math.tan(x)
Return the tangent of x radians.

所以可以用這三個數學函數來繪製。但是Python有比上面函式還好用的程式庫,叫做NumPy。使用NumPy可以快速產生繪圖資料。接下來要處理繪圖的功能,在 Python 的程式庫中,有Matplotlib可用,就用此程式庫來繪圖囉。

範例程式:

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
# 產生x座標的資料,從 -PI 到 PI
X = np.linspace(-np.pi, np.pi, 260, endpoint=True)
# Y座標
Cos_y, Sin_y = np.cos(X), np.sin(X)
Tan_y = np.tan(X)
plt.plot(X, Cos_y, color="red", linewidth=1.0, linestyle="-", label="Cos")
plt.plot(X, Sin_y, color="green", linewidth=1.0, linestyle="--", label="Sin")
plt.plot(X, Tan_y, color="blue", linewidth=1.0, linestyle=":", label="Tan")
# 設定 y 座標範圍
plt.ylim(-2.0, 2.0)
# 設定 x 座標文字
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
plt.legend(bbox_to_anchor=(1, 1), loc=1, borderaxespad=0.)
plt.show()


輸出圖:

沒有留言: