我在 python 中使用 matplotlib 绘制散点图。我想根据某些函数为点着色,如下所示:
import matplotlib.pyplot as plt
def color(x, y):
# based on some rules, return a color
if(condition):
return 'red'
else:
return 'blue'
plt.scatter(index, data) #c= something?
我知道 matplotlib.from_levels_and_colors
函数,但问题是映射不是基于 x 或 y 轴上值的水平。函数计算出的每个数据点都有第三个值,这就是我要根据这些点着色的值。
有办法吗?
最佳答案
为什么不直接让 c
数组成为默认颜色图的指示器函数。例如:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(100)
y = np.arange(100)
# Colors whether or not x+y is a multiple of 5
c = (x + y)%5 == 0
# Use 'jet' colormap for red/blue.
plt.scatter(x, y, c=c, cmap='jet')
当然,您可以使用将映射到 0 和 1 的不同极值的颜色图。
如果您想要的结果有超过 2 种颜色,那么将具有许多不同值的数组作为 c
传递是完全没问题的(并且不需要标准化)。参见 here举个例子。
关于python - 基于matplotlib中函数的自定义颜色映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34299118/