如何在 matplotlib 中制作按密度着色的散点图? [英] How can I make a scatter plot colored by density in matplotlib?
问题描述
我想制作一个散点图,其中每个点都由附近点的空间密度着色.
I'd like to make a scatter plot where each point is colored by the spatial density of nearby points.
我遇到了一个非常相似的问题,它显示了一个使用 R 的例子:
I've come across a very similar question, which shows an example of this using R:
使用 matplotlib 在 python 中完成类似任务的最佳方法是什么?
What's the best way to accomplish something similar in python using matplotlib?
推荐答案
除了@askewchan 建议的 hist2d
或 hexbin
之外,您还可以使用与您链接到的问题中已接受的答案.
In addition to hist2d
or hexbin
as @askewchan suggested, you can use the same method that the accepted answer in the question you linked to uses.
如果你想这样做:
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
# Generate fake data
x = np.random.normal(size=1000)
y = x * 3 + np.random.normal(size=1000)
# Calculate the point density
xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)
fig, ax = plt.subplots()
ax.scatter(x, y, c=z, s=100)
plt.show()
如果您希望按密度顺序绘制点,以便最密集的点始终位于顶部(类似于链接示例),只需按 z 值对它们进行排序.我还将在这里使用较小的标记尺寸,因为它看起来更好一些:
If you'd like the points to be plotted in order of density so that the densest points are always on top (similar to the linked example), just sort them by the z-values. I'm also going to use a smaller marker size here as it looks a bit better:
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
# Generate fake data
x = np.random.normal(size=1000)
y = x * 3 + np.random.normal(size=1000)
# Calculate the point density
xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)
# Sort the points by density, so that the densest points are plotted last
idx = z.argsort()
x, y, z = x[idx], y[idx], z[idx]
fig, ax = plt.subplots()
ax.scatter(x, y, c=z, s=50)
plt.show()
这篇关于如何在 matplotlib 中制作按密度着色的散点图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!