Python绘制极坐标方程

标签 python numpy matplotlib math plot

我在使用 matplotlib 在 python 中绘制极坐标方程时遇到问题。

按照我的理解,我要创建一个变量来表示 theta.. 或将在绘图中使用的所有角度。在我的例子中,从 0 到 2(pi),中间有 1000 步。

然后我应该能够将极坐标方程输入为 R 并绘制它。

我的问题是我知道这个等式*应该是一个圆。但是我的代码没有绘制圆圈。

*r = 2sinθ + 2cosθ

这是 wolfram alpha 生成的结果,我知道这是正确的图形,与我的结果对比

Wolfram Alpha Expected graph

Result of my python code Python output

现在,如果我将 r 改为:

r = abs(2 * np.cos(theta) + 2 * np.sin(theta))

生成的图如图所示here

这个图“上半部分”是我从我的原始代码中得到的,但无法弄清楚为什么这个图会产生一个心形而不是一个圆

import numpy as np
from matplotlib import pyplot as plt

#Produce theta variable
theta = np.arange(0, 2*np.pi, .01)[1:]

#Input polar equation of 2sinθ + 2cosθ 
r = 2 * np.cos(theta) + 2 * np.sin(theta) 
# Adding "()" around eq doesn't change anything

#Make plt figure
fig = plt.figure()

#Make sub-plot with attribute "polar"
ax = fig.add_subplot(polar=True)

#Plot function
ax.plot(theta, r)

#Show plot
plt.show()

最佳答案

主要的混淆是 Matplotlib 不会在负侧绘制负 r 值。相反,它的 r 范围从 -3 到 3,并在同一侧绘制所有内容。

通过将负 r 的 theta 旋转 180º 并取 r 的绝对值,您可以获得更常规的解释:

import numpy as np
from matplotlib import pyplot as plt

theta = np.arange(0, 2 * np.pi, .01)[1:]
r = 2 * np.cos(theta) + 2 * np.sin(theta)

fig = plt.figure()
ax = fig.add_subplot(polar=True)

# change negative r values to positive, rotating theta by 180º
theta = np.where(r >= 0, theta, theta + np.pi)
r = np.abs(r)
ax.plot(theta, r)

plt.show()

rotating theta 180º for negative r

这是另一个示例,显示默认值和将负 r 值移动到另一侧之间的区别,使用 r = theta - pi 表示 theta 02 pi 之间。 r 为正的曲线部分用蓝色绘制,负的用红色绘制。注意 r 轴的标签:从 -33 为默认值,从 03 为修改后的版本。 (对于原始示例,红色和蓝色曲线占据相同的位置。)

import numpy as np
from matplotlib import pyplot as plt

theta = np.arange(0, 2 * np.pi, .01)[1:]
r = theta - np.pi
positive_r = r >= 0

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5), subplot_kw={'polar': True})

for ax in (ax1, ax2):
    if ax == ax2:
        # change negative r values to positive, rotating theta by 180º
        theta = np.where(r >= 0, theta, theta + np.pi)
        r = np.abs(r)
    ax.plot(theta[positive_r], r[positive_r], color='skyblue')
    ax.plot(theta[~positive_r], r[~positive_r], color='tomato')
ax1.set_title('Default: negative $r$\non same side as $theta$')
ax2.set_title('Negative $r$ on other side')

plt.show()

comparing polar plots with negative r

关于Python绘制极坐标方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68850221/

相关文章:

python - 将两个数据框合并到一个公共(public)索引上(无需创建单独的行)

python - 如何统计文件中每个数字开头的数字出现的次数? (Python)

python - 在迭代所有形式时选择正确的形式

python - numpy:以移位方式将数组相加

python - 可视化部分相关性

Python ipywidgets : create a savefig button

二维矩阵中的python索引

python - 发现 numpy 多年来百分比变化减少

Python numpy 数组的列加法与移位

python - Matplotlib:调整刻度以适合图形