How can I move a tick label only(without moving corresponding tick)?

前端 未结 3 1875
暖寄归人
暖寄归人 2021-01-11 10:31

I\'m using matplotlib to generate a diagram, and I use set_ticks and set_ticklabels to mark out several important values on the x-axis. But some of

相关标签:
3条回答
  • 2021-01-11 10:50

    From your comment "..mark out several important values on the x-axis" I think you shouldn't be changing the xticks and labels, but rather add vertical lines with appropriate annotation.

    This means the grid over which your data remains regular and allows you to colourise important points, you could also add the numeric values as well fairly easily.

    Example

    import pylab as py
    
    # Plot a sinc function
    delta=2.0
    x=py.linspace(-10,10,100)
    y=py.sinc(x-delta)
    
    # Mark delta
    py.axvline(delta,ls="--",color="r")
    py.annotate(r"$\delta$",xy=(delta+0.2,-0.2),color="r",size=15)
    py.plot(x,y) 
    

    Simple sinc and annotation

    0 讨论(0)
  • 2021-01-11 10:50

    For someone looking for an answer to the original question: It could be an option to change the alignment of the tick_label.

    This is explained in detail in an example on the matplotlib webpage. Basically in the case above one would use

    ax.get_xaxis().majorTicks[1].label1.set_horizontalalignment('right')
    ax.get_xaxis().majorTicks[2].label1.set_horizontalalignment('left')
    

    to move the labels away from each other

    0 讨论(0)
  • 2021-01-11 11:06

    As a strict response to the question asked, you can get the specific tick and use set_pad()

    ax.get_xaxis().majorTicks[2].set_pad()
    

    I think that a better practice would be to use autofmt_xdate

    fig = plt.figure()
    fig.autofmt_xdate()
    

    Which rotates the xtick labels nicely and allow most texts to fit nicely without overlapping.
    If they still overlap - it means that those ticks are very close together. And then the question which arises is what good would two ticks so closely together would do to the viewer of your plot?

    0 讨论(0)
提交回复
热议问题