Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

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

I have a figure with a log axis

enter image description here

and I would like to relabel the axis ticks with logs of the values, rather than the values themselves

enter image description here

The way I've accomplished this is with

plt.axes().set_xticklabels([math.log10(x) for x in plt.axes().get_xticks()])

but I wonder if there isn't a less convoluted way to do this.

What is the correct idiom for systematically relabeling ticks on matplotlib plots with values computed from the original tick values?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...