与完整数据集中的maplotlib分散数据和颜色标记的子集

时间:2019-03-01 17:21:46

标签: python matplotlib plot

问题

我有一些(x, y, z)坐标。借助这些,我可以分散(x, y)坐标,并根据z坐标的值为标记着色。

但是,我想绘制(x, y)坐标的一个子集,但要根据z坐标的整个集合来对标记进行着色。

MWE

让我们生成一些(x, y, z)点,绘制所有数据,然后绘制数据的某些子集。

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal

# generate some random data
x = np.random.uniform(-1, 1, size=100)
y = np.random.uniform(-1, 1, size=100)
z = multivariate_normal.pdf(np.vstack([x, y]).T, mean=np.zeros(2))

# scatter plot of all data
fig, ax = plt.subplots(1, 2, figsize=[5, 2])
ax[0].scatter(x, y, c=z)
ax[0].set_xlim([-1, 1]); ax[0].set_ylim([-1, 1])
ax[0].set_title('Full dataset')

# scatter plot of subset of data
d = (x**2 + y**2)**.5
ax[1].scatter(x[d < 0.75], y[d < 0.75], c=z[d < 0.75])
ax[1].set_xlim([-1, 1]); ax[1].set_ylim([-1, 1])
ax[1].set_title('Subset')

这给出了下面的图:

enter image description here

当然,子集中图中的点的颜色与完整数据集中的点不同。但是,我希望它们的颜色相同。

所需的输出

enter image description here

我尝试过的

我尝试绘制和着色整个数据集,然后使用白色标记在不需要的点上绘制。但是,这种方法意味着白色标记会遮挡整个数据集中的点。我考虑过绘制完整的数据集,然后使用get_offsets()方法以某种方式删除不需要的点,但这似乎和我的第一个想法一样有点棘手。有一种简单的方法可以实现我的愿望吗?

1 个答案:

答案 0 :(得分:1)

感谢@Tacratis为我指出此问题的正确方向。此后我就解决了。

事实证明,plt.scatter可以接受参数vminvmax,将颜色标准化为任何所需的比例!

因此:

# scatter plot of all data
fig, ax = plt.subplots(1, 2, figsize=[5, 2])
ax[0].scatter(x, y, c=z)
ax[0].set_xlim([-1, 1]); ax[0].set_ylim([-1, 1])
ax[0].set_title('Full dataset')

# desired result
ax[1].scatter(x[d < 0.75], y[d < 0.75], c=z[d < 0.75], vmin=z.min(), vmax=z.max())
ax[1].set_xlim([-1, 1]); ax[1].set_ylim([-1, 1])
ax[1].set_title('Desired subset')

fig.tight_layout()

进行款待,并创建所需的情节: enter image description here