Matplotlib Scatter plot filter color (Colorbar)

*爱你&永不变心* 提交于 2019-12-19 11:40:18

问题


I have some data let say x, y, and z. All are 1D arrays. I have done a scatter plot with z as color as;

 import matplotlib.pyplot as plt
 plt.scatter(x,y,c=z,alpha = 0.2)
 plt.xlabel("X")
 plt.ylabel("Y")
 plt.ylim((1.2,1.5))
 plt.colorbar() 

The z values are normalized and its between -1 to 1. I have attached the figure below.

The question I have is; How can I filter the colors such that let say the points that have a color value between -0.25 to 0.25 disappear form the figure (i.e set the color to white).

The values for x, y, and z can be provided if needed to answer this question. Thank you for your time.


回答1:


import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)

# prepare random data
stats = -1, 1, 200
x = np.random.uniform(*stats)
y = np.random.uniform(*stats)
z = np.random.uniform(*stats)

# mask unwanted data
thresh = 0.4
mask = np.abs(z) <= thresh
x_ma = np.ma.masked_where(mask, x)
y_ma = np.ma.masked_where(mask, y)
z_ma = np.ma.masked_where(mask, z)

And do the plotting:

fig, (ax_left, ax_right) = plt.subplots(1, 2, figsize=(10, 4),
                                        sharex=True, sharey=True)
img_left = ax_left.scatter(x, y, c=z)
fig.colorbar(img_left, ax=ax_left)
img_right = ax_right.scatter(x_ma, y_ma, c=z_ma)
fig.colorbar(img_right, ax=ax_right)

gives following result:

The plot on the right side hides all points that fall below the chosen threshold.



来源:https://stackoverflow.com/questions/28577924/matplotlib-scatter-plot-filter-color-colorbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!