Color axis spine with multiple colors using matplotlib

后端 未结 2 914
生来不讨喜
生来不讨喜 2020-12-11 12:19

Is it possible to color axis spine with multiple colors using matplotlib in python?

Desired output style:

2条回答
  •  时光取名叫无心
    2020-12-11 12:38

    Here is a slightly different solution. If you don't want to recolor the complete axis, you can use zorder to make sure the colored line segments are visible on top of the original axis.

    After drawing the main plot:

    • save the x and y limits
    • draw a horizontal line at ylims[0] between the chosen x-values with the desired color
    • clipping should be switched off to allow the line to be visible outside the strict plot area
    • zorder should be high enough to put the new line in front of the axes
    • the saved x and y limits need to be put back, because drawing extra lines moved them (alternatively, you might have turned off autoscaling the axes limits by calling plt.autoscale(False) before drawing the colored axes)
    from matplotlib import pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 20, 100)
    for i in range(10):
        plt.plot(x, np.sin(x*(1-i/50)), c=plt.cm.plasma(i/12))
    
    xlims = plt.xlim()
    ylims = plt.ylim()
    plt.hlines(ylims[0], 0, 10, color='limegreen', lw=1, zorder=4, clip_on=False)
    plt.hlines(ylims[0], 10, 20, color='crimson', lw=1, zorder=4, clip_on=False)
    plt.vlines(xlims[0], -1, 0, color='limegreen', lw=1, zorder=4, clip_on=False)
    plt.vlines(xlims[0], 0, 1, color='crimson', lw=1, zorder=4, clip_on=False)
    plt.xlim(xlims)
    plt.ylim(ylims)
    
    plt.show()
    

    To highlight an area on the x-axis, also axvline or axvspan can be interesting. An example:

    from matplotlib import pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 25, 100)
    for i in range(10):
        plt.plot(x, np.sin(x)*(1-i/20), c=plt.cm.plasma(i/12))
    plt.axvspan(10, 20, color='paleturquoise', alpha=0.5)
    plt.show()
    

提交回复
热议问题