我有一个二维数组,它定义笛卡尔坐标中的值。我正在尝试将其转换为极坐标,并制作极地热图。我添加了一些玩具数据,只是为了使其更具可读性(我的实际数据是一个非常大的 numpy 数组)。
我尝试运行下面的代码,但生成的图是不对称的,这不是我所期望的。这让我相信我从根本上误解了使用 pcolormesh 或 meshgrid 的正确方法。
import numpy as np
import matplotlib.pyplot as plt
x = [-1, 0, 1]
y = [-1, 0, 1]
z = [[0, 0, 0], [0, 1, 0], [0, 0, 0]] #some data
def cart2pol(x, y):
xx, yy = np.meshgrid(x,y)
rho = np.sqrt(xx**2 + yy**2)
temp_phi = np.arctan2(yy, xx) * 180 / np.pi
phi = np.arctan2(yy, xx) * 180 / np.pi
for i in range(0,len(x)):
for j in range(0,len(y)):
if temp_phi[i][j] < 0:
phi[i][j] = temp_phi[i][j] + 360
else:
phi[i][j] = temp_phi[i][j]
return rho, phi
def polar_plot(z):
fig = plt.figure()
rho, phi = cart2pol(x,y)
plt.subplot(projection="polar")
plt.pcolormesh(phi, rho, z)
plt.plot(phi, rho, color='k', ls='none')
plt.grid()
plt.show()
cart2pol(x, y)
polar_plot(z)
cart2pol 函数的输出如下所示:
rho = [[1.41421356, 1. , 1.41421356],
[1. , 0. , 1. ],
[1.41421356, 1. , 1.41421356]]
phi = [[225., 270., 315.],
[180., 0., 0.],
[135., 90., 45.]]
这正是我所期望的输入。这让我相信问题出在 Polar_plot() 上。
我希望看到一个对称的结果,这表明我正确使用了极坐标图函数,但是生成的图与我的预期非常不同。
输出:
Output from above code
numpy 中的弧函数给出的角度已经以弧度为单位,因此不需要转换它们。
import numpy as np
import matplotlib.pyplot as plt
x = [-1, 0, 1]
y = [-1, 0, 1]
z = [[1,0,1], [2,1,0], [1,0,1]] #some data
def cart2pol(x, y):
xx, yy = np.meshgrid(x,y)
rho = np.sqrt(xx**2 + yy**2)
temp_phi = np.arctan2(yy, xx)
phi = np.arctan2(yy, xx)
for i in range(0,len(x)):
for j in range(0,len(y)):
if temp_phi[i][j] < 0:
phi[i][j] = temp_phi[i][j] + 2*np.pi
else:
phi[i][j] = temp_phi[i][j]
return rho, phi
def polar_plot(z):
fig = plt.figure()
rho, phi = cart2pol(x,y)
plt.subplot(projection="polar")
plt.pcolormesh(phi, rho, z)
#plt.pcolormesh(th, z, r)
plt.plot(phi, rho, color='k', ls='none')
plt.grid()
plt.show()
cart2pol(x, y)
polar_plot(z)
结果:
我是一名优秀的程序员,十分优秀!