matplotlib使用list更改线段上的线宽

时间:2013-11-08 14:57:29

标签: python matplotlib

我希望能够根据值列表更改线条的宽度。例如,如果我有以下列表来绘制:

a = [0.0,1.0,2.0,3.0,4.0]

我可以使用以下列表来设置线宽吗?

b = [1.0,1.5,3.0,2.0,1.0]

似乎没有得到支持,但是他们说“一切皆有可能”,所以我想问一下有更多经验的人(noob here)。

由于

1 个答案:

答案 0 :(得分:9)

基本上,您有两种选择。

  1. 使用LineCollection。在这种情况下,您的线宽将以磅为单位,并且每个线段的线宽将保持不变。
  2. 使用多边形(最简单的fill_between,但对于复杂的曲线,您可能需要直接创建它)。在这种情况下,您的线宽将以数据单位表示,并且会在您的线条中的每个线段之间呈线性变化。
  3. 以下是两者的例子:

    行集合示例


    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection
    np.random.seed(1977)
    
    x = np.arange(10)
    y = np.cos(x / np.pi)
    width = 20 * np.random.random(x.shape)
    
    # Create the line collection. Widths are in _points_!  A line collection
    # consists of a series of segments, so we need to reformat the data slightly.
    coords = zip(x, y)
    lines = [(start, end) for start, end in zip(coords[:-1], coords[1:])]
    lines = LineCollection(lines, linewidths=width)
    
    fig, ax = plt.subplots()
    ax.add_collection(lines)
    ax.autoscale()
    plt.show()
    

    enter image description here

    多边形示例:


    import numpy as np
    import matplotlib.pyplot as plt
    np.random.seed(1977)
    
    x = np.arange(10)
    y = np.cos(x / np.pi)
    width = 0.5 * np.random.random(x.shape)
    
    fig, ax = plt.subplots()
    ax.fill_between(x, y - width/2, y + width/2)
    plt.show()
    

    enter image description here