Python绘制极坐标方程

mat*_*ous 3 python math plot numpy matplotlib

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

\n

按照我的理解,我将创建一个代表 theta 的变量..或绘图中使用的所有角度。就我而言,从 0 到 2(pi),中间有 1000 个步骤。

\n

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

\n

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

\n
\n

*r = 2sin\xce\xb8 + 2cos\xce\xb8

\n
\n

这是 Wolfram alpha 产生的结果,我知道这是正确的图表,与我的结果

\n
\n

沃尔夫勒姆·阿尔法预期图

\n
\n
\n

我的Python代码的结果我的Python代码Python输出

\n
\n

现在,如果我将 r 更改为:

\n
\n

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

\n
\n

生成的图表如图所示所示

\n

该图的“上半部分”是我对原始代码的期望,并且无法弄清楚为什么该图产生心形而不是圆形

\n
import numpy as np\nfrom matplotlib import pyplot as plt\n\n#Produce theta variable\ntheta = np.arange(0, 2*np.pi, .01)[1:]\n\n#Input polar equation of 2sin\xce\xb8 + 2cos\xce\xb8 \nr = 2 * np.cos(theta) + 2 * np.sin(theta) \n# Adding "()" around eq doesn\'t change anything\n\n#Make plt figure\nfig = plt.figure()\n\n#Make sub-plot with attribute "polar"\nax = fig.add_subplot(polar=True)\n\n#Plot function\nax.plot(theta, r)\n\n#Show plot\nplt.show()\n
Run Code Online (Sandbox Code Playgroud)\n

Joh*_*anC 6

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

\n

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

\n
import numpy as np\nfrom matplotlib import pyplot as plt\n\ntheta = np.arange(0, 2 * np.pi, .01)[1:]\nr = 2 * np.cos(theta) + 2 * np.sin(theta)\n\nfig = plt.figure()\nax = fig.add_subplot(polar=True)\n\n# change negative r values to positive, rotating theta by 180\xc2\xba\ntheta = np.where(r >= 0, theta, theta + np.pi)\nr = np.abs(r)\nax.plot(theta, r)\n\nplt.show()\n
Run Code Online (Sandbox Code Playgroud)\n

旋转 theta 180\xc2\xba 以获得负 r

\n

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

\n
import numpy as np\nfrom matplotlib import pyplot as plt\n\ntheta = np.arange(0, 2 * np.pi, .01)[1:]\nr = theta - np.pi\npositive_r = r >= 0\n\nfig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5), subplot_kw={\'polar\': True})\n\nfor ax in (ax1, ax2):\n    if ax == ax2:\n        # change negative r values to positive, rotating theta by 180\xc2\xba\n        theta = np.where(r >= 0, theta, theta + np.pi)\n        r = np.abs(r)\n    ax.plot(theta[positive_r], r[positive_r], color=\'skyblue\')\n    ax.plot(theta[~positive_r], r[~positive_r], color=\'tomato\')\nax1.set_title(\'Default: negative $r$\\non same side as $theta$\')\nax2.set_title(\'Negative $r$ on other side\')\n\nplt.show()\n
Run Code Online (Sandbox Code Playgroud)\n

比较带有负 r 的极坐标图

\n