Matplotlib animate fill_between shape

后端 未结 5 2107
别那么骄傲
别那么骄傲 2021-01-04 02:48

I am trying to animate a fill_between shape inside matplotlib and I don\'t know how to update the data of the PolyCollection. Take this simple example: I have two lines and

5条回答
  •  醉话见心
    2021-01-04 02:51

    initialize pyplot interactive mode

    import matplotlib.pyplot as plt
    
    plt.ion()
    

    use the optional label argument when plotting the fill:

    plt.fill_between(
        x, 
        y1, 
        y2, 
        color="yellow", 
        label="cone"
    )
    
    plt.pause(0.001) # refresh the animation
    

    later in our script we can select by label to delete that specific fill or a list of fills, thus animating on a object by object basis.

    axis = plt.gca()
    
    fills = ["cone", "sideways", "market"]   
    
    for collection in axis.collections:
        if str(collection.get_label()) in fills:
            collection.remove()
            del collection
    
    plt.pause(0.001)
    

    you can use the same label for groups of objects you would like to delete; or otherwise encode the labels with tags as needed to suit needs

    for example if we had fills labelled:

    "cone1" "cone2" "sideways1"

    if "cone" in str(collection.get_label()):
    

    would sort to delete both those prefixed with "cone".

    You can also animate lines in the same manner

    for line in axis.lines:
    

提交回复
热议问题