使用 matplotlib 和 python 绘制所有三角函数 (x^2 + y^2 == 1)

Plotting all of a trigonometric function (x^2 + y^2 == 1) with matplotlib and python

作为学习 Matplotlib 和改进 math/coding 的练习,我决定尝试绘制一个三角函数(x 平方加 y 平方等于一)。

三角函数也称为"circular"函数,但我只生成了一半的圆。

#Attempt to plot equation x^2 + y^2 == 1

import numpy as np
import matplotlib.pyplot as plt
import math

x = np.linspace(-1, 1, 21)  #generate np.array of X values -1 to 1 in 0.1 increments
x_sq = [i**2 for i in x]

y = [math.sqrt(1-(math.pow(i, 2))) for i in x]   #calculate y for each value in x
y_sq = [i**2 for i in y]

#Print for debugging / sanity check
for i,j in zip(x_sq, y_sq):
    print('x: {:1.4f}    y: {:1.4f}         x^2: {:1.4f}    y^2: {:1.4f}         x^2 + Y^2 = {:1.4f}'.format(math.sqrt(i), math.sqrt(j), i, j, i+j))

#Format how the chart displays
plt.figure(figsize=(6, 4))
plt.axhline(y=0, color='y')
plt.axvline(x=0, color='y')
plt.grid()

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

plt.show()

我想绘制完整的圆。我的代码只产生正 y 值,我想绘制整个圆。

完整的情节应该是这样的。我使用 Wolfram Alpha 来生成它。

理想情况下,我不想要为我完成提升的解决方案,例如使用 matplotlib.pyplot.contour。作为学习练习,我想"see the working"这么说。也就是说,理想情况下我想生成所有值并绘制它们 "manually".

我能想到的唯一方法是重新排列方程并生成一组负 y 值和计算出的 x 值,然后分别绘制它们。我相信有更好的方法来实现结果,我相信 Stack Overflow 上的一位专家会知道这些选项是什么。

如有任何帮助,我们将不胜感激。 :-)

等式x**2 + y**2 = 1描述了一个围绕原点半径为1的圆。 但是假设你还不知道这个,你仍然可以尝试用极坐标写这个方程,

x = r*cos(phi)
y = r*sin(phi)
(r*cos(phi))**2 + (r*sin(phi))**2 == 1
r**2*(cos(phi)**2 + sin(phi)**2) == 1

由于三角恒等式 cos(phi)**2 + sin(phi)**2 == 1 这减少到

r**2 == 1

并且由于 r 应该是真实的,

r == 1

(对于任何 phi)。

将其插入 python:

import numpy as np
import matplotlib.pyplot as plt

phi = np.linspace(0, 2*np.pi, 200)
r = 1
x = r*np.cos(phi)
y = r*np.sin(phi)
plt.plot(x,y)
plt.axis("equal")
plt.show()

发生这种情况是因为平方根 return 只有正值,所以您需要将这些值转换为负值。

你可以这样做:

import numpy as np
import matplotlib.pyplot as plt

r = 1 # radius 
x = np.linspace(-r, r, 1000)
y = np.sqrt(r-x**2)

plt.figure(figsize=(5,5), dpi=100) # figsize=(n,n), n needs to be equal so the image doesn't flatten out
plt.grid(linestyle='-', linewidth=2)
plt.plot(x, y, color='g')
plt.plot(x, -y, color='r')
plt.legend(['Positive y', 'Negative y'], loc='lower right')
plt.axhline(y=0, color='b')
plt.axvline(x=0, color='b')
plt.show()

那应该return这个PLOT