【问题标题】:Plotting multiple segments with colors based on some variable with matplotlib使用 matplotlib 基于某些变量绘制具有颜色的多个段
【发布时间】:2014-12-30 19:25:18
【问题描述】:

根据Matplotlib: Plotting numerous disconnected line segments with different colorsmatplotlib: 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。

提前谢谢你!

【问题讨论】:

    标签: python python-2.7 matplotlib plot data-analysis


    【解决方案1】:

    你可以使用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()
    

    【讨论】:

    • 你能解释一下lineslc的代码吗?
    【解决方案2】:

    您可以考虑以下几点:

    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()
    

    请记住,当呈现介于 0 和 1 之间的数字时,颜色图 pl.cm.hot(0.7) 将返回一个颜色值。这有时非常方便,就像您的情况一样

    编辑:

    对于红到绿的颜色图:

    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()
    

    【讨论】:

    • 这很好用,谢谢,有没有办法使用个人色标代替 pl.cm?例如,如果我想要红色为 0,绿色为 1,比如设置我自己的颜色图。谢谢。
    • 您可以使用LinearSegmentedColormap。这里有几个详细的教程matplotlib.org/api/… 和这里wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps 这样做。
    • 我已经为您的简单方案展示了一个实现。此外,如果这对您有用,您可以考虑接受答案。 :)
    • 谢谢,这很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    相关资源
    最近更新 更多