如何在matplotlib中绘制以密度着色的散点图? [英] How can I make a scatter plot colored by density in matplotlib?

查看:749
本文介绍了如何在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:

R散点图:符号颜色表示重叠点的数量

使用matplotlib在python中完成类似操作的最佳方法是什么?

What's the best way to accomplish something similar in python using matplotlib?

推荐答案

除了@askewchan建议的hist2dhexbin之外,您还可以使用与链接到的问题中的已接受答案相同的方法.

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, edgecolor='')
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, edgecolor='')
plt.show()

这篇关于如何在matplotlib中绘制以密度着色的散点图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆