Plotting phase portraits in Python using polar coordinates

末鹿安然 提交于 2021-02-10 14:26:48

问题


I need a phase portrait of the following nonlinear system given in polar form...

\dot{r} = 0.5*(r - r^3)
\dot{\theta} = 1

I know how to do it in Mathematica...

field1 = {0.5*(r - r^3), 1};
p1 = StreamPlot[Evaluate@TransformedField["Polar" -> "Cartesian", field1, {r, \[Theta]} -> {x, y}], {x, -3, 3}, {y, -3, 3}, Axes -> True, StreamStyle -> Gray, ImageSize -> Large];
Show[p1, AxesLabel->{x,y}, ImageSize -> Large]

How can I do the same using pyplot.quiver in Python?


回答1:


Just very naive implementation, but could be helpful...

import numpy as np
import matplotlib.pyplot as plt

def dF(r, theta):
    return 0.5*(r - r**3), 1

X, Y = np.meshgrid(np.linspace(-3.0, 3.0, 30), np.linspace(-3.0, 3.0, 30))
u, v = np.zeros_like(X), np.zeros_like(X)
NI, NJ = X.shape

for i in range(NI):
    for j in range(NJ):
        x, y = X[i, j], Y[i, j]
        r, theta = (x**2 + y**2)**0.5, np.arctan2(y, x)
        fp = dF(r, theta)
        u[i,j] = (r + fp[0]) * np.cos(theta + fp[1]) - x
        v[i,j] = (r + fp[0]) * np.sin(theta + fp[1]) - y

plt.streamplot(X, Y, u, v)
plt.axis('square')
plt.axis([-3, 3, -3, 3])
plt.show()




回答2:


Correction of the previous answer:

  • From x=r*cos(theta) one gets dx = dr*cos(theta)-r*sin(theta)*dtheta = x*dr/r-y*dtheta,
  • From y=r*sin(theta) one gets dy = dr*sin(theta)+r*cos(theta)*dtheta = y*dr/r+x*dtheta,
  • one can use the vectorized operations of numpy to avoid all loops
def dF(r, theta):
    return 0.5*r*(1 - r*r), 1+0*theta

X, Y = np.meshgrid(np.linspace(-3.0, 3.0, 30), np.linspace(-3.0, 3.0, 30))
R, Theta = (X**2 + Y**2)**0.5, np.arctan2(Y, X)
dR, dTheta = dF(R, Theta)
C, S = np.cos(Theta), np.sin(Theta)
U, V = dR*C - R*S*dTheta, dR*S+R*C*dTheta

plt.streamplot(X, Y, U, V, color='r', linewidth=0.5, density=1.6)
plt.axis('square')
plt.axis([-3, 3, -3, 3])
plt.show()

This gives the plot below. Use the density option of streamplot to increase the density of plot lines.



来源:https://stackoverflow.com/questions/58701195/plotting-phase-portraits-in-python-using-polar-coordinates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!