Modify tick label text

前端 未结 10 1303
遥遥无期
遥遥无期 2020-11-22 07:13

I want to make some modifications to a few selected tick labels in a plot.

For example, if I do:

label = axes.yaxis.get_major_ticks()[2].label
label         


        
10条回答
  •  隐瞒了意图╮
    2020-11-22 08:11

    Caveat: Unless the ticklabels are already set to a string (as is usually the case in e.g. a boxplot), this will not work with any version of matplotlib newer than 1.1.0. If you're working from the current github master, this won't work. I'm not sure what the problem is yet... It may be an unintended change, or it may not be...

    Normally, you'd do something along these lines:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    
    # We need to draw the canvas, otherwise the labels won't be positioned and 
    # won't have values yet.
    fig.canvas.draw()
    
    labels = [item.get_text() for item in ax.get_xticklabels()]
    labels[1] = 'Testing'
    
    ax.set_xticklabels(labels)
    
    plt.show()
    

    enter image description here

    To understand the reason why you need to jump through so many hoops, you need to understand a bit more about how matplotlib is structured.

    Matplotlib deliberately avoids doing "static" positioning of ticks, etc, unless it's explicitly told to. The assumption is that you'll want to interact with the plot, and so the bounds of the plot, ticks, ticklabels, etc will be dynamically changing.

    Therefore, you can't just set the text of a given tick label. By default, it's re-set by the axis's Locator and Formatter every time the plot is drawn.

    However, if the Locators and Formatters are set to be static (FixedLocator and FixedFormatter, respectively), then the tick labels stay the same.

    This is what set_*ticklabels or ax.*axis.set_ticklabels does.

    Hopefully that makes it slighly more clear as to why changing an individual tick label is a bit convoluted.

    Often, what you actually want to do is just annotate a certain position. In that case, look into annotate, instead.

提交回复
热议问题