Increment matplotlib color cycle

后端 未结 3 1176
野趣味
野趣味 2021-02-20 14:43

Is there a simple way to increment the matplotlib color cycle without digging into axes internals?

When plotting interactively a common pattern I use is:



        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-20 15:18

    You could call

    ax2._get_lines.get_next_color()
    

    to advance the color cycler on color. Unfortunately, this accesses the private attribute ._get_lines, so this is not part of the official public API and not guaranteed to work in future versions of matplotlib.

    A safer but less direct way of advance the color cycler would be to plot a null plot:

    ax2.plot([], [])
    

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.arange(10)
    y1 = np.random.randint(10, size=10)
    y2 = np.random.randint(10, size=10)*100
    fig, ax = plt.subplots()
    ax.plot(x, y1, label='first')
    ax2 = ax.twinx()
    ax2._get_lines.get_next_color()
    # ax2.plot([], [])
    ax2.plot(x,y2, label='second')
    
    handles1, labels1 = ax.get_legend_handles_labels()
    handles2, labels2 = ax2.get_legend_handles_labels()
    ax.legend(handles1+handles2, labels1+labels2, loc='best')  
    
    plt.show()
    

提交回复
热议问题