pandas 带有 matplotlib 散射的条件颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42453649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conditional color with matplotlib scatter
提问by MattnDo
I have the following Pandas Dataframe, where column a represents a dummy variable:
我有以下 Pandas 数据框,其中 a 列代表一个虚拟变量:


What I would like to do is to give my markers a cmap='jet'color following the value of column b, except when the value in column ais equal to 1 - in this case I want it to be the color grey.
我想要做的是在cmap='jet'column 的值之后给我的标记一个颜色b,除非column 中的值a等于 1 - 在这种情况下,我希望它是灰色。
Any idea how I can do this?
知道我该怎么做吗?
采纳答案by Serenity
You have to mark your values which are equal to one and plot:
您必须标记等于 1 的值并绘制:
import matplotlib.pyplot as plt
import numpy as np
# test data
t = np.linspace(0, 2 * np.pi, 30)
x = np.sin(t)
x[3] = 1
y = np.cos(t)
# indices for 'bad' values
indices = x == 1
# calc colors from jet cmap
cmap = plt.get_cmap('jet')
colors = cmap((y - y.min()) / y.ptp())
# normal values
plt.scatter(t[~indices], x[~indices], c = colors[~indices], cmap = cmap)
# bad values
plt.scatter(t[indices], x[indices], c = 'grey')
plt.show()
Arrays t, x, y represent pandas series.
数组 t, x, y 代表Pandas系列。

