如何在Matplotlib中计算极坐标图密度并实现按密度着色散点图?
Hey there! Let's break down what's going wrong with your polar scatter plot and how to fix it to get that crisp, density-colored visualization you're aiming for.
Why sorting leads to unexpected results (Figure 2)
The core issue in your code is a mismatch between the coordinates you're plotting and the density values you're using for coloring. Let's walk through your code step-by-step:
- You calculate the density values
zcorrectly usinggaussian_kde. - You sort the indices by density and create sorted versions of your x (
saccade_orientation_PP), y (saccade_amplitude_PP), and z values. - But then you plot the original unsorted coordinates, paired with the sorted z values!
This means each original point is getting assigned a density value that belongs to a completely different point, leading to the scrambled, incorrect look in Figure 2. The sorting step itself is a good idea (we want densest points plotted last so they're on top), but you just didn't use the sorted coordinates in your scatter plot.
Fixed code for the desired density-colored plot
Here's the corrected version of your code, with the key fix highlighted:
import numpy as np import matplotlib.pyplot as plt from scipy.stats import gaussian_kde # Calculate the point density: Saccade Orientation is an angle, Amplitude is the radial value xy = np.vstack([saccade_orientation_PP, saccade_amplitude_PP]) z = gaussian_kde(xy)(xy) # Sort the points by density, so that the densest points are plotted last idx = z.argsort() x_sorted, y_sorted, z_sorted = np.array(saccade_orientation_PP)[idx], np.array(saccade_amplitude_PP)[idx], z[idx] ax1 = plt.subplot(121, polar=True) # Use the SORTED coordinates and matching sorted density values here ax1.scatter(x_sorted, y_sorted, c=z_sorted, edgecolor='', alpha=0.75) # Optional: Add a colorbar to show density scale plt.colorbar(label='Point Density') plt.show()
What this fixes:
- Now each point's color corresponds to its own calculated density value, eliminating mismatches.
- By plotting the least dense points first and densest points last, dense clusters will be visible on top of sparser points, making your Figure 1-style data much clearer.
Extra tips for better polar density visualization
- Use a perceptually uniform colormap like
cmap='viridis'(add it to thescattercall) to make density differences easier to interpret. - Adjust the
alphavalue if you have a lot of points: lower values (like 0.5) let overlapping points blend naturally while still showing density. - If your angle data wraps around (0 to 2π), ensure
gaussian_kdeaccounts for circularity if needed—though for most visualization cases, the standard implementation works well.
内容的提问来源于stack exchange,提问作者bigPoppa350

