Adding an arbitrary line to a matplotlib plot in ipython notebook

后端 未结 5 1354
孤独总比滥情好
孤独总比滥情好 2020-12-07 14:41

I\'m rather new to both python/matplotlib and using it through the ipython notebook. I\'m trying to add some annotation lines to an existing graph and I can\'t figure out ho

5条回答
  •  半阙折子戏
    2020-12-07 15:02

    Rather than abusing plot or annotate, which will be inefficient for many lines, you can use matplotlib.collections.LineCollection:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection
    
    np.random.seed(5)
    x = np.arange(1, 101)
    y = 20 + 3 * x + np.random.normal(0, 60, 100)
    plt.plot(x, y, "o")
    
    # Takes list of lines, where each line is a sequence of coordinates
    l1 = [(70, 100), (70, 250)]
    l2 = [(70, 90), (90, 200)]
    lc = LineCollection([l1, l2], color=["k","blue"], lw=2)
    
    plt.gca().add_collection(lc)
    
    plt.show()
    

    Figure with two lines plotted via LineCollection

    It takes a list of lines [l1, l2, ...], where each line is a sequence of N coordinates (N can be more than two).

    The standard formatting keywords are available, accepting either a single value, in which case the value applies to every line, or a sequence of M values, in which case the value for the ith line is values[i % M].

提交回复
热议问题