使用 matplotlib 绘制极坐标函数

问题描述 投票:0回答:2

我正在尝试使用 matplotlib 绘制此函数。

正如您在 Desmos 应用程序中看到的那样,方程正确地将函数绘制为圆,但是当我尝试将其移植到 Python 时,我得到了这个:

import numpy as np
import matplotlib.pyplot as plt

def fungsi_r4(theta, theta0, r0, a):
  return r0 * np.cos(theta - theta0) + np.sqrt((a ** 2) - (r0 ** 2) * (np.sin(theta - theta0) ** 2))

theta = np.linspace(0, 2 * np.pi, 100)
r = fungsi_r4(theta, 2.4, 5.1, 2.6)

ax = plt.subplot(projection='polar')
ax.plot(theta, r)

我的感觉告诉我它与从函数返回的负值有关但我不知道如何处理它。

python numpy matplotlib polar-coordinates
2个回答
0
投票

这个

r
的方程是 Desmos 中唯一使用的数学表达式吗?我认为这个等式代表了一些问题的解决方案。

例子:
也许一些曲线与几个圆的交点......
也许圆圈不以

theta = 0
r = 0
为中心...

入住Desmos...

import numpy as np
import matplotlib.pyplot as plt

def fungsi_r4(theta, theta0, r0, a):
  return r0 * np.cos(theta - theta0) + np.sqrt(a**2 - r0**2 * (np.sin(theta - theta0) ** 2))


theta = np.linspace(0., 2 * np.pi, 50)

a1 = 5.1
a2 = 10.2

r1 = fungsi_r4(theta, 2.4, 5.1, a1)
r2 = fungsi_r4(theta, 2.4, 5.1, a2)
r3 = np.full(theta.shape, 5.1)

ax = plt.subplot(projection='polar')
ax.plot(theta, r1, ls='', marker='x', c='blue', label='a = {:.2f}'.format(a1))
ax.plot(theta, r2, ls='', marker='x', c='red', label='a = {:.2f}'.format(a2))
ax.plot(theta, r3, ls='', marker='x', c='black', label='centered and r constant')
plt.legend()
plt.show()


0
投票

不同之处在于这两个程序如何处理负半径:Desmos 通过原点将它们翻转回来,而 matplotlib 将径向比例扩展到负数。

这里有一些代码可以像 Desmos 那样修改数据点:

def flip_negative_radii(theta, r):
    flip_mask = r < 0
    r[flip_mask] *= -1
    theta[flip_mask] = (theta[flip_mask] - np.pi) % (2*np.pi)
    return theta, r

用法示例:

import numpy as np
import matplotlib.pyplot as plt

def fungsi_r4(theta, theta0, r0, a):
    return r0 * np.cos(theta - theta0) + np.sqrt((a ** 2) - (r0 ** 2) * (np.sin(theta - theta0) ** 2))

theta = np.linspace(0, 2 * np.pi, 100)
r = fungsi_r4(theta, 2.4, 5.1, 2.6)

ax = plt.subplot(projection='polar')
ax.plot(*flip_negative_radii(theta, r))
plt.show()

差距是由于平方根中的项变为负数并产生 NaN。如果可能的话,我会尝试提出函数的参数表示,这将避免这两个问题。

© www.soinside.com 2019 - 2024. All rights reserved.