根据Matplotlib: Plotting numerous disconnected line segments with different colors和matplotlib: how to change data points color based on some variable这两个主题的答案,我试图绘制一个列表给出的一组段,例如:
data = [(-118, -118), (34.07, 34.16),
(-117.99, -118.15), (34.07, 34.16),
(-118, -117.98), (34.16, 34.07)]
我想用基于第二个列表的颜色绘制每个段:
color_param = [9, 2, 21]
带有色彩图。到目前为止,我使用此行显示段:
plt.plot(*data)
我期待像
这样的东西plt.plot(*data, c=color_param, cmap='hot')
会起作用,但事实并非如此。任何人都可以帮我解决这个问题吗?如果可能的话,我宁愿使用matplotlib。
提前谢谢!
答案 0 :(得分:3)
您可以使用LineCollection
,这是一个示例:
import pylab as pl
import numpy as np
from matplotlib.collections import LineCollection
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
c = np.cos(x)
lines = np.c_[x[:-1], y[:-1], x[1:], y[1:]]
lc = LineCollection(lines.reshape(-1, 2, 2), array=c, linewidths=3)
fig, ax = pl.subplots()
ax.add_collection(lc)
ax.set_xlim(x.min(), x.max())
ax.set_ylim(y.min(), y.max())
fig.show()
答案 1 :(得分:0)
您可以考虑以下事项:
import numpy as np
import pylab as pl
# normalize this
color_param = np.array([9.0, 2.0, 21.0])
color_param = (color_param - color_param.min())/(color_param.max() - color_param.min())
data = [(-118, -118), (34.07, 34.16),
(-117.99, -118.15), (34.07, 34.16),
(-118, -117.98), (34.16, 34.07)]
startD = data[::2]
stopD = data[1::2]
for start, stop, col in zip( startD, stopD, color_param):
pl.plot( start, stop, color = pl.cm.jet(col) )
pl.show()
记得色彩图pl.cm.hot(0.7)
在显示0到1之间的数字时会返回一个颜色值。有时会非常方便,就像你的情况一样
编辑:
对于红色到绿色的色彩映射:
import pylab as pl
import matplotlib.colors as col
import numpy as np
cdict = {'red': [(0.0, 1.0, 1.0),
(1.0, 0.0, 0.0)],
'green': [(0.0, 0.0, 0.0),
(1.0, 1.0, 1.0)],
'blue': [(0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)]}
my_cmap = col.LinearSegmentedColormap('my_colormap',cdict,256)
for theta in np.linspace(0, np.pi*2, 30):
pl.plot([0,np.cos(theta)], [0,np.sin(theta)], color=my_cmap(theta/(2*np.pi)) )
pl.show()