Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scatterplot and combined polar histogram in matplotlib

I am attempting to produce a plot like this which combines a cartesian scatter plot and a polar histogram. (Radial lines optional) enter image description here A similar solution (by Nicolas Legrand) exists for looking at differences in x and y (code here), but we need to look at ratios (i.e. x/y). enter image description here

More specifically, this is useful when we want to look at the relative risk measure which is the ratio of two probabilities.

The scatter plot on it's own is obviously not a problem, but the polar histogram is more advanced.

The most promising lead I have found is this central example from the matplotlib gallery here enter image description here

I have attempted to do this, but have run up against the limits of my matplotlib skills. Any efforts moving towards this goal would be great.

like image 987
Ben Vincent Avatar asked Oct 16 '25 18:10

Ben Vincent


1 Answers

I'm sure that others will have better suggestions, but one method that gets something like you want (without the need for extra axes artists) is to use a polar projection with a scatter and bar chart together. Something like

import matplotlib.pyplot as plt
import numpy as np

x = np.random.uniform(size=100)
y = np.random.uniform(size=100)

r = np.sqrt(x**2 + y**2)
phi = np.arctan2(y, x)

h, b = np.histogram(phi, bins=np.linspace(0, np.pi/2, 21), density=True)
colors = plt.cm.Spectral(h / h.max())

ax = plt.subplot(111, projection='polar')
ax.scatter(phi, r, marker='.')
ax.bar(b[:-1], h, width=b[1:] - b[:-1], 
       align='edge', bottom=np.max(r) + 0.2,  color=colors)
# Cut off at 90 degrees
ax.set_thetamax(90)
# Set the r grid to cover the scatter plot
ax.set_rgrids([0, 0.5, 1])
# Let's put a line at 1 assuming we want a ratio of some sort
ax.set_thetagrids([45], [1])

which will give enter image description here

It is missing axes labels and some beautification, but it might be a place to start. I hope it is helpful.

like image 122
tomjn Avatar answered Oct 19 '25 08:10

tomjn