What is the correct way to replace matplotlib tick labels with computed values?

后端 未结 1 1508
不思量自难忘°
不思量自难忘° 2020-12-15 11:07

I have a figure with a log axis

\"enter

and I would like to relabel the axis t

相关标签:
1条回答
  • 2020-12-15 11:32

    Look into the Formatter classes. Unless you are putting text on your ticks you should almost never directly use set_xticklabels or set_yticklabels. This completely de-couples your tick labels from you data. If you adjust the view limits, the tick labels will remain the same.

    In your case, a formatter already exists for this:

    fig, ax = plt.subplots()
    ax.loglog(np.logspace(0, 5), np.logspace(0, 5)**2)
    ax.xaxis.set_major_formatter(matplotlib.ticker.LogFormatterExponent())
    

    matplotlib.ticker.LogFormatterExponent doc

    In general you can use FuncFormatter. For an example of how to use FuncFomatter see matplotlib: change yaxis tick labels which one of many examples floating around SO.

    A concise example for what you want, lifting exactly from JoeKington in the comments,:

    ax.xaxis.set_major_formatter(
       FuncFormatter(lambda x, pos: '{:0.1f}'.format(log10(x))))
    
    0 讨论(0)
提交回复
热议问题