首页 文章

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

提问于
浏览
5

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

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 回答

  • 9

    基本上,您有两种选择 .

    • 使用 LineCollection . 在这种情况下,您的线宽将以点为单位,并且每个线段的线宽将保持不变 .

    • 使用多边形(最简单的是 fill_between ,但对于复杂的曲线,您可能需要直接创建它) . 在这种情况下,您的线宽将以数据单位表示,并且会在您的线条中的每个线段之间线性变化 .

    以下是两者的示例:

    行集合示例


    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

相关问题