使用 matplotlib 散点图的条件颜色
Conditional color with matplotlib scatter
我有以下 Pandas 数据框,其中 a 列代表一个虚拟变量:
我想做的是在 b
列的值之后为我的标记提供 cmap='jet'
颜色,除非 a
列中的值等于 1 -在这种情况下,我希望它是灰色。
知道我该怎么做吗?
您必须标记等于 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()
数组 t、x、y 代表 pandas 个系列。
我有以下 Pandas 数据框,其中 a 列代表一个虚拟变量:
我想做的是在 b
列的值之后为我的标记提供 cmap='jet'
颜色,除非 a
列中的值等于 1 -在这种情况下,我希望它是灰色。
知道我该怎么做吗?
您必须标记等于 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()
数组 t、x、y 代表 pandas 个系列。