问题描述
遵循这两个主题的答案和,我正在尝试绘制列表给出的一组细分,例如:
Following the answers of both topics Matplotlib: Plotting numerous disconnected line segments with different colors and matplotlib: how to change data points color based on some variable, I am trying to plot a set of segments given by a list, for instance:
data = [(-118, -118), (34.07, 34.16),
(-117.99, -118.15), (34.07, 34.16),
(-118, -117.98), (34.16, 34.07)]
,我想用基于第二个列表的颜色,例如:
and I would like to plot each segments with a color based on a second list for instance:
color_param = [9, 2, 21]
带有颜色映射。到目前为止,我正在使用此行显示分段:
with a colormap. So far I am using this line to display the segments:
plt.plot(*data)
我期待的是类似
plt.plot(*data, c=color_param, cmap='hot')
可以但事实并非如此。有人可以帮我解决这个问题吗?如果可能的话,我宁愿使用matplotlib。
would work but it doesn't. Can anybody help me solving this problem? I would rather work with matplotlib if possible.
预先感谢您!
推荐答案
您可以考虑以下内容:
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之间的数字时返回一个颜色值。这有时非常方便,例如您的情况
Rememebr that the colormaps pl.cm.hot(0.7)
will return a color value when presented a number between 0 and 1. This comes in very handy sometimes, like in your case
编辑:
对于红色到绿色的色图:
For a red-to-green colormap:
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()
这篇关于使用matplotlib根据某些变量用颜色绘制多个线段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!