mat*_*ous 3 python math plot numpy matplotlib
我在使用 matplotlib 在 python 中绘制极坐标方程时遇到问题。
\n按照我的理解,我将创建一个代表 theta 的变量..或绘图中使用的所有角度。就我而言,从 0 到 2(pi),中间有 1000 个步骤。
\n然后我应该能够输入极坐标方程 R 并绘制它。
\n我的问题是我知道这个方程*应该是一个圆。但我的代码没有绘制一个圆圈。
\n\n\n*r = 2sin\xce\xb8 + 2cos\xce\xb8
\n
这是 Wolfram alpha 产生的结果,我知道这是正确的图表,与我的结果
\n\n\n沃尔夫勒姆·阿尔法预期图
\n
\n\n我的Python代码的结果我的Python代码Python输出
\n
现在,如果我将 r 更改为:
\n\n\nr = abs(2 * np.cos(theta) + 2 * np.sin(theta))
\n
生成的图表如图所示所示
\n该图的“上半部分”是我对原始代码的期望,并且无法弄清楚为什么该图产生心形而不是圆形
\nimport 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
主要的困惑是 Matplotlib 不会在负端绘制负 r 值。相反,它使 r 范围从 -3 到 3 并将所有内容绘制在同一侧。
\n您可以通过将负 r 的 theta 旋转 180\xc2\xba 并取 r 的绝对值来获得更常规的解释:
\nimport 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\nr
这是另一个示例,显示默认值和将负值移动到另一侧之间的差异,使用r = theta - pi
for theta
Between0
和2 pi
。曲线中正的部分r
用蓝色绘制,负的部分用红色绘制。请注意轴的标签r
:从-3
到3
表示默认版本,从0
到3
表示修改版本。(在原始示例中,红色和蓝色曲线占据相同的位置。)
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\n