【问题标题】:Matplotlib - contour and quiver plot in projected polar coordinatesMatplotlib - 投影极坐标中的等高线和颤动图
【发布时间】:2016-10-08 20:51:03
【问题描述】:

我需要绘制在 (r,theta) 坐标中的不均匀网格上定义的标量和矢量场的等高线和颤动图。

作为我遇到的问题的一个最小示例,考虑磁偶极子的 Stream function 的等高线图,这种函数的等高线是相应矢量场的流线(在这种情况下,磁场)。

以下代码采用 (r,theta) 坐标中的不均匀网格,将其映射到笛卡尔平面并绘制流函数的等高线图。

import numpy as np
import matplotlib.pyplot as plt

r = np.logspace(0,1,200)
theta = np.linspace(0,np.pi/2,100)

N_r = len(r)
N_theta = len(theta)

# Polar to cartesian coordinates
theta_matrix, r_matrix = np.meshgrid(theta, r)
x = r_matrix * np.cos(theta_matrix)
y = r_matrix * np.sin(theta_matrix)

m = 5
psi = np.zeros((N_r, N_theta))

# Stream function for a magnetic dipole
psi = m * np.sin(theta_matrix)**2 / r_matrix

contour_levels = m * np.sin(np.linspace(0, np.pi/2,40))**2.

fig, ax = plt.subplots()
# ax.plot(x,y,'b.')  # plot grid points
ax.set_aspect('equal')
ax.contour(x, y, psi, 100, colors='black',levels=contour_levels)
plt.show()

但由于某种原因,我得到的情节看起来不正确:

如果我在轮廓函数调用中交换 x 和 y,我会得到想要的结果:

当我尝试制作在同一网格上定义并映射到 x-y 平面的 矢量场 的颤动图时,也会发生同样的事情,只是在函数调用中交换 x 和 y 不再起作用.

好像我在某个地方犯了一个愚蠢的错误,但我不知道是什么。

【问题讨论】:

    标签: python numpy matplotlib contour polar-coordinates


    【解决方案1】:

    如果psi = m * np.sin(theta_matrix)**2 / r_matrix 然后 psi 随着 theta 从 0 变为 pi/2 而增加,而 psi 随着 r 增加而减小。

    所以 psi 的等高线应该随着 theta 的增加而增加 r。结果 在从中心向外辐射时逆时针方向的曲线中。这是 与您发布的第一个情节一致,并且您的代码的第一个版本返回的结果与

    ax.contour(x, y, psi, 100, colors='black',levels=contour_levels)
    

    确认结果合理性的另一种方法是查看psi 的曲面图:

    import numpy as np
    import matplotlib.pyplot as plt
    import mpl_toolkits.mplot3d.axes3d as axes3d
    
    r = np.logspace(0,1,200)
    theta = np.linspace(0,np.pi/2,100)
    
    N_r = len(r)
    N_theta = len(theta)
    
    # Polar to cartesian coordinates
    theta_matrix, r_matrix = np.meshgrid(theta, r)
    x = r_matrix * np.cos(theta_matrix)
    y = r_matrix * np.sin(theta_matrix)
    
    m = 5
    
    # Stream function for a magnetic dipole
    psi = m * np.sin(theta_matrix)**2 / r_matrix
    
    contour_levels = m * np.sin(np.linspace(0, np.pi/2,40))**2.
    
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1, projection='3d')
    ax.set_aspect('equal')
    
    ax.plot_surface(x, y, psi, rstride=8, cstride=8, alpha=0.3)
    ax.contour(x, y, psi, colors='black',levels=contour_levels)
    plt.show()
    

    【讨论】:

    • 你说得对,我犯了一个愚蠢的错误,情节没有错,偶极子场是正确的。出于某种原因,我希望它在 (r, theta) 平面上以不同的方式定向。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    相关资源
    最近更新 更多