matplotlib axis arrow tip

后端 未结 5 2076
执念已碎
执念已碎 2020-12-14 18:23

I am trying to set an arrow at the end of a an axis in matplotlib. I don\'t want to remove the spines and replace them with pure arrows because I need their functionalities

5条回答
  •  [愿得一人]
    2020-12-14 19:00

    You could remove all spines and expand the arrows to cover the data range (found this code here):

    import matplotlib.pyplot as plt
    import numpy as np
    
    def arrowed_spines(fig, ax):
    
        xmin, xmax = ax.get_xlim() 
        ymin, ymax = ax.get_ylim()
    
        # removing the default axis on all sides:
        for side in ['bottom','right','top','left']:
            ax.spines[side].set_visible(False)
    
        # removing the axis ticks
        plt.xticks([]) # labels 
        plt.yticks([])
        ax.xaxis.set_ticks_position('none') # tick markers
        ax.yaxis.set_ticks_position('none')
    
        # get width and height of axes object to compute 
        # matching arrowhead length and width
        dps = fig.dpi_scale_trans.inverted()
        bbox = ax.get_window_extent().transformed(dps)
        width, height = bbox.width, bbox.height
    
        # manual arrowhead width and length
        hw = 1./20.*(ymax-ymin) 
        hl = 1./20.*(xmax-xmin)
        lw = 1. # axis line width
        ohg = 0.3 # arrow overhang
    
        # compute matching arrowhead length and width
        yhw = hw/(ymax-ymin)*(xmax-xmin)* height/width 
        yhl = hl/(xmax-xmin)*(ymax-ymin)* width/height
    
        # draw x and y axis
        ax.arrow(xmin, 0, xmax-xmin, 0., fc='k', ec='k', lw = lw, 
                 head_width=hw, head_length=hl, overhang = ohg, 
                 length_includes_head= True, clip_on = False) 
    
        ax.arrow(0, ymin, 0., ymax-ymin, fc='k', ec='k', lw = lw, 
                 head_width=yhw, head_length=yhl, overhang = ohg, 
                 length_includes_head= True, clip_on = False)
    
    
    # plot
    x = np.arange(-2., 10.0, 0.01)
    plt.plot(x, x**2)
    fig = plt.gcf()
    fig.set_facecolor('white') 
    ax = plt.gca()
    
    arrowed_spines(fig, ax)
    
    plt.show()
    

提交回复
热议问题