Ian Gullett
Ian Gullett

Reputation: 137

How to plot a 2d cartesian array as a polar heatmap

I have a 2d array which defines values in cartesian coordinates. I'm trying to convert it to polar coordinates, and make a polar heatmap. I've included some toy data just to make this more readable (my actual data is a very large numpy array).

I've tried to run the code below, but the plot that is produced is asymmetric which is not what I would expect. This leads me to believe I'm fundamentally misunderstanding the proper way to use either pcolormesh or 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)

The output of the cart2pol function looks like this:

rho = [[1.41421356, 1.        , 1.41421356],
       [1.        , 0.        , 1.        ],
       [1.41421356, 1.        , 1.41421356]]

phi = [[225., 270., 315.],
       [180.,   0.,   0.],
       [135.,  90.,  45.]]

which is exactly what I would expect given the inputs. This leads me to believe that the problem lies in polar_plot().

I'd expect to see a symmetric result which would indicate that I'm using the polar plot function correctly, however the plot produced is very unlike what I'd expect.

Output:

Output from above code

Upvotes: 1

Views: 1948

Answers (1)

user11563547
user11563547

Reputation:

The angles given by the arc-functions in numpy are already in radians, so you don't need to convert them.

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)

Result: enter image description here

Upvotes: 1

Related Questions