【问题标题】:Python plotting polar equationPython绘制极坐标方程
【发布时间】:2021-10-21 07:15:35
【问题描述】:

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

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

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

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

*r = 2sinθ + 2cosθ

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

Wolfram 阿尔法Expected graph

我的python代码的结果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()

【问题讨论】:

标签: python numpy matplotlib math plot


【解决方案1】:

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

对于负 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()

这是另一个示例,显示默认值和将负 r 值移动到另一侧之间的区别,在 02 pi 之间使用 r = theta - pi 表示 thetar 为正的曲线部分以蓝色绘制,负数以红色绘制。注意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()

【讨论】:

  • 太棒了。这正是我一直在寻找的。不太确定我是否理解其背后的数学原理。但我会调查一下。非常感谢!
【解决方案2】:

如果我正确理解你想要什么,你可以用极坐标表达你的曲线,但你应该用笛卡尔坐标convert它。

x = r*np.cos(theta)
y = r*np.sin(theta)

这样,笛卡尔坐标中的绘图调用给出了圆:

fig = plt.figure(figsize = (5, 5))
ax = fig.add_subplot(polar = False)
ax.plot(x, y)

在极坐标中给出:

fig = plt.figure(figsize = (5, 5))
ax = fig.add_subplot(polar = True)
ax.plot(x, y)

【讨论】:

  • 是否完全需要将其转换为笛卡尔?我有一个不同的方程,它以极坐标形式相当完美地表示。 (r=np.sqrt(4*np.sin(2*theta)))。但如果这是表示这张图的最佳方式,那我当然会转换它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-01
  • 2019-01-26
相关资源
最近更新 更多