如何根据某些变量更改数据点颜色 [英] How to change data points color based on some variable
问题描述
我有 2 个随时间 (t) 变化的变量 (x,y).我想绘制 x 与 t 的关系,并根据 y 的值为刻度线着色.例如对于 y 的最大值,刻度颜色为深绿色,最小值为深红色,对于中间值,颜色将在绿色和红色之间缩放.
这可以用 python 中的 matplotlib 完成吗?
这就是
可以指定自定义颜色映射和规范
cmap, norm = mcolors.from_levels_and_colors([0, 2, 5, 6], ['red', 'green', 'blue'])plt.scatter(x, y, c=t, cmap=cmap, norm=norm)
I have 2 variables (x,y) that change with time (t). I want to plot x vs. t and color the ticks based on the value of y. e.g. for highest values of y the tick color is dark green, for lowest value is dark red, and for intermediate values the color will be scaled in between green and red.
Can this be done with matplotlib in python?
This is what matplotlib.pyplot.scatter
is for.
If no colormap is specified, scatter
will use whatever the default colormap is set to. To specify which colormap scatter should use, use the cmap
kwarg (e.g. cmap="jet"
).
As a quick example:
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
# Generate data...
t = np.linspace(0, 2 * np.pi, 20)
x = np.sin(t)
y = np.cos(t)
plt.scatter(t, x, c=y, ec='k')
plt.show()
One may specify a custom color map and norm
cmap, norm = mcolors.from_levels_and_colors([0, 2, 5, 6], ['red', 'green', 'blue'])
plt.scatter(x, y, c=t, cmap=cmap, norm=norm)
这篇关于如何根据某些变量更改数据点颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!