【问题标题】:Can I make a multi-color line in matplotlib?我可以在 matplotlib 中制作多色线吗?
【发布时间】:2016-05-24 05:11:12
【问题描述】:

我正在尝试创建具有特定条件的彩色线。基本上,我希望在 y 轴上指向下方时将线设为红色,在指向上方时将线设为绿色,当两者都没有时设为蓝色。

我尝试了一些我发现的类似示例,但我从未能够将它们转换为与轴上的 plot() 一起使用。只是想知道如何做到这一点。

这是我目前想出的一些代码:

#create x,y coordinates
x = numpy.random.choice(10,10)
y = numpy.random.choice(10,10)

#create an array of colors based on direction of line (0=r, 1=g, 2=b)
colors = []
#create an array that is one position away from original 
#to determine direction of line 
yCopy = list(y[1:])
for y1,y2 in zip(y,yCopy):
    if y1 > y2:
        colors.append(0)
    elif y1 < y2:
        colors.append(1)
    else:
        colors.append(2)
#add tenth spot to array as loop only does nine
colors.append(2)

#create a numpy array of colors
categories = numpy.array(colors)

#create a color map with the three colors
colormap = numpy.array([matplotlib.colors.colorConverter.to_rgb('r'),matplotlib.colors.colorConverter.to_rgb('g'),matplotlib.colors.colorConverter.to_rgb('b')])

#plot line
matplotlib.axes.plot(x,y,color=colormap[categories])

不确定如何让 plot() 接受颜色数组。我总是收到关于用作颜色的格式类型的错误。尝试了十六进制、十进制、字符串和浮点数。与 scatter() 完美搭配。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    有一个example on the matplotlib page 显示如何使用LineCollection 绘制一条多色线。

    剩下的问题是获取线条集合的颜色。所以如果y 是要比较的值,

    cm = dict(zip(range(-1,2,1),list("gbr")))
    colors = list( map( cm.get , np.sign(np.diff(y))  ))
    

    完整代码:

    import numpy as np; np.random.seed(5)
    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection
    
    x = np.arange(10)
    y = np.random.choice(10,10)
    
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    
    cm = dict(zip(range(-1,2,1),list("rbg")))
    colors = list( map( cm.get , np.sign(np.diff(y))  ))
    
    lc = LineCollection(segments, colors=colors, linewidths=2)
    fig, ax = plt.subplots()
    ax.add_collection(lc)
    
    ax.autoscale()
    ax.margins(0.1)
    plt.show()
    

    【讨论】:

      【解决方案2】:

      好的。所以我想出了如何使用 LineCollecion 在轴上画线。

      import numpy as np
      import pylab as pl
      from matplotlib import collections  as mc
      
      segments = []
      colors = np.zeros(shape=(10,4))
      x = range(10)
      y = np.random.choice(10,10)
      i = 0
      
      for x1, x2, y1,y2 in zip(x, x[1:], y, y[1:]):
          if y1 > y2:
              colors[i] = tuple([1,0,0,1])
          elif y1 < y2:
              colors[i] = tuple([0,1,0,1])
          else:
              colors[i] = tuple([0,0,1,1])
          segments.append([(x1, y1), (x2, y2)])
          i += 1     
      
      lc = mc.LineCollection(segments, colors=colors, linewidths=2)
      fig, ax = pl.subplots()
      ax.add_collection(lc)
      ax.autoscale()
      ax.margins(0.1)
      pl.show()
      

      【讨论】:

        【解决方案3】:

        我认为您不能在 plot 中使用颜色数组(文档说颜色可以是任何 matlab 颜色,而 scatter 文档说您可以使用数组)。

        但是,您可以通过分别绘制每一行来伪造它:

        import numpy
        from matplotlib import pyplot as plt
        
        x = range(10)
        y = numpy.random.choice(10,10)
        for x1, x2, y1,y2 in zip(x, x[1:], y, y[1:]):
            if y1 > y2:
                plt.plot([x1, x2], [y1, y2], 'r')
            elif y1 < y2:
                plt.plot([x1, x2], [y1, y2], 'g')
            else:
                plt.plot([x1, x2], [y1, y2], 'b')
        
        plt.show()
        

        【讨论】:

        • 哈哈。那将是我的下一次尝试。感谢您的回复!
        • 其实它可以用 LineCollection 来完成,但我不明白如何让它适应我的需要。
        猜你喜欢
        • 2016-04-28
        • 2018-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-13
        相关资源
        最近更新 更多