# matplotlib中的散点图和组合极坐标直方图

``````import numpy as np
import matplotlib.pyplot as plt

# Scatter data
n = 50
x = 0.3 + np.random.randn(n)*0.1
y = 0.4 + np.random.randn(n)*0.02

"""Scatter plot with radial histogram of x/y ratios"""

# Axis setup
fig = plt.figure(figsize=(6,6))
ax2.set_rorigin(-20)
ax2.set_thetamax(90)

# define useful constant

def rotate_hist_axis(ax):
"""rotate so that 0 degrees is pointing up and right"""
ax.set_thetamin(-45)
ax.set_thetamax(45)
return ax

# Convert scatter data to histogram data
r = np.sqrt(x**2 + y**2)
phi = np.arctan2(y, x)
h, b = np.histogram(phi,
bins=np.linspace(0, np.pi/2, n_hist_bins),
density=True)

# SCATTER PLOT -------------------------------------------------------
ax1.scatter(x,y)

ax1.set(xlim=[0, 1], ylim=[0, 1], xlabel="x", ylabel="y")
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)

# HISTOGRAM ----------------------------------------------------------
ax2 = rotate_hist_axis(ax2)
# rotation of axis requires rotation in bin positions

# plot the histogram
bars = ax2.bar(b[:-1], h, width=b[1:] - b[:-1], align='edge')

def update_hist_ticks(ax, desired_ratios):
"""Update tick positions and corresponding tick labels"""
x = np.ones(len(desired_ratios))
y = 1/desired_ratios
# define ticklabels
xticklabels = [str(round(float(label), 2)) for label in desired_ratios]
ax2.set(xticks=phi, xticklabels=xticklabels)
return ax

ax2 = update_hist_ticks(ax2, np.array([1/8, 1/4, 1/2, 1, 2, 4, 8]))

# just have radial grid lines
ax2.grid(which="major", axis="y")

# remove bin count labels
ax2.set_yticks([])

return (fig, [ax1, ax2])

``````

0条评论