我有2个随时间(t)变化的变量(x,y)。我想绘制x与t的关系,并根据y的值为滴答声着色。例如对于y的最高值,刻度颜色为深绿色,最低值为深红色,对于中间值,颜色将在绿色和红色之间缩放。
可以用python中的matplotlib完成吗?
答案 0 :(得分:70)
这是matplotlib.pyplot.scatter
的用途。
作为一个简单的例子:
import matplotlib.pyplot as plt
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)
plt.show()
答案 1 :(得分:1)
如果你想绘制线而不是点,请参见this example,在此处修改以根据需要绘制代表函数的好/坏点作为黑/红:
def plot(xx, yy, good):
"""Plot data
Good parts are plotted as black, bad parts as red.
Parameters
----------
xx, yy : 1D arrays
Data to plot.
good : `numpy.ndarray`, boolean
Boolean array indicating if point is good.
"""
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
from matplotlib.colors import from_levels_and_colors
from matplotlib.collections import LineCollection
cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
points = np.array([xx, yy]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lines = LineCollection(segments, cmap=cmap, norm=norm)
lines.set_array(good.astype(int))
ax.add_collection(lines)
plt.show()