Skip to content Skip to sidebar Skip to footer

Polar Histogram In Python For Given R, Theta And Z Values

I have a dataframe consisting of measurements from a particular magnetometer station over time, with columns corresponding to: its latitude (which I think of as a radius) its azim

Solution 1:

Calculating a histogram is easily done with numpy.histogram2d. Plotting the resulting 2D array can be done with matplotlib's pcolormesh.

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt

# two input arrays
azimut = np.random.rand(3000)*2*np.pi
radius = np.random.rayleigh(29, size=3000)

# define binning
rbins = np.linspace(0,radius.max(), 30)
abins = np.linspace(0,2*np.pi, 60)

#calculate histogram
hist, _, _ = np.histogram2d(azimut, radius, bins=(abins, rbins))
A, R = np.meshgrid(abins, rbins)

# plot
fig, ax = plt.subplots(subplot_kw=dict(projection="polar"))

pc = ax.pcolormesh(A, R, hist.T, cmap="magma_r")
fig.colorbar(pc)

plt.show()

enter image description here

Solution 2:

This appears to be what you're looking for: https://physt.readthedocs.io/en/latest/special_histograms.html#Polar-histogram

from physt import histogram, binnings, special
import numpy as np
import matplotlib.pyplot as plt

# Generate some points in the Cartesian coordinates
np.random.seed(42)

x = np.random.rand(1000)
y = np.random.rand(1000)
z = np.random.rand(1000)

# Create a polar histogram with default parameters
hist = special.polar_histogram(x, y)
ax = hist.plot.polar_map()

Polar histogram created with physt

The docs linked include more examples with colors, bin sizing etc.

Edit: I think this is going to take a bit of munging to get your data into the right shape, but I think this example illustrates the library's capabilities and can be adjusted to your use case:

import random
import numpy as np
import matplotlib.pyplot as plt
from physt import special

# Generate some points in the Cartesian coordinates
np.random.seed(42)

gen = lambda l, h, s = 3000: np.asarray([random.random() * (h - l) + l for _ inrange(s)])

X = gen(-100, 100)
Y = gen(-1000, 1000)
Z = gen(0, 1400)

hist = special.polar_histogram(X, Y, weights=Z, radial_bins=40)
# ax = hist.plot.polar_map()

hist.plot.polar_map(density=True, show_zero=False, cmap="inferno", lw=0.5, figsize=(5, 5))
plt.show()

Example with color & custom coordinates

Post a Comment for "Polar Histogram In Python For Given R, Theta And Z Values"