Python - 随机对一系列点进行部分采样至p

2024-04-26 10:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个列表,x和{},我希望在散点图中一起绘制。在

列表包含的数据点太多。我想要一个点更少的图。我不能裁剪修剪这些列表,我需要从这两个列表中随机细分一组点。最好的办法是什么?在


Tags: 数据列表绘制细分办法
3条回答

您可以使用

idx = np.random.choice(np.arange(len(x)), num_samples)
plt.scatter(x[idx], y[idx])

然而,这让结果有点取决于随机运气。我们可以通过making a heatmap做得更好。^{}使这一点特别容易:

^{pr2}$

下面是一个比较这两种方法的示例:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

np.random.seed(2015)
N = 10**5
val1 = np.random.normal(loc=10, scale=2,size=N)
val2 = np.random.normal(loc=0, scale=1, size=N)

fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True)
cmap = plt.get_cmap('jet')
norm = mcolors.LogNorm()

num_samples = 10**4
idx = np.random.choice(np.arange(len(val1)), num_samples)
ax[0].scatter(val1[idx], val2[idx])
ax[0].set_title('subsample')

im = ax[1].hexbin(val1, val2, gridsize=50, cmap=cmap, norm=norm)
ax[1].set_title('hexbin heatmap')

plt.tight_layout()
fig.colorbar(im, ax=ax.ravel().tolist())

plt.show()

{1美元^

您可以使用random.sample()

max_points = len(x)

# Assuming you only want 50 points.
random_indexes = random.sample(range(max_points), 50)

new_x = [x[i] for i in random_indexes]
new_y = [y[i] for i in random_indexes]

可以使用随机索引掩码从xy中随机选取

import numpy as np
import matplotlib.pyplot as plt


N = 50
x = np.random.rand(N)
y = np.random.rand(N)

# Pick random 10 samples, 2 means two choices from [0, 1] for the mask
subsample = np.random.choice(2, 10).astype(bool)      
plt.scatter(x[subsample], y[subsample])
plt.show()

或者,您可以使用hist2d来绘制二维直方图,它使用密度而不是数据点

^{pr2}$

相关问题 更多 >