Color axis spine with multiple colors using matplotlib

后端 未结 2 916
生来不讨喜
生来不讨喜 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:44

    You can use a LineCollection to create a multicolored line. You can then use the xaxis-transform to keep it fixed to the xaxis, independent of the y-limits. Setting the actual spine invisible and turning clip_on off makes the LineCollection look like the axis spine.

    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection
    import numpy as np
    
    fig, ax = plt.subplots()
    
    colors=["b","r","lightgreen","gold"]
    x=[0,.25,.5,.75,1]
    y=[0,0,0,0,0]
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lc = LineCollection(segments,colors=colors, linewidth=2,
                                   transform=ax.get_xaxis_transform(), clip_on=False )
    ax.add_collection(lc)
    ax.spines["bottom"].set_visible(False)
    ax.set_xticks(x)
    plt.show()
    

提交回复
热议问题