用计算值替换matplotlib刻度标签的正确方法是什么? [英] What is the correct way to replace matplotlib tick labels with computed values?

查看:133
本文介绍了用计算值替换matplotlib刻度标签的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有对数轴的图形

I have a figure with a log axis

并且我想用值的日志而不是值本身重新标记轴刻度

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

我做到这一点的方法是

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.

用从原始报价值计算出的值来系统地重新标记matplotlib图上的报价的正确习惯是什么?

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

推荐答案

查看 Formatter 类.除非您在刻度上加上文字,否则几乎永远不要直接使用set_xticklabelsset_yticklabels.这样可以完全将剔号标签与数据脱钩.如果您调整视图限制,则刻度线标签将保持不变.

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文档

通常,您可以使用FuncFormatter.有关如何使用FuncFomatter的示例,请参见 matplotlib:更改yaxis刻度标签围绕SO浮动的众多示例之一.

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.

一个简单的示例,它完全符合JoeKington的评论:

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

这篇关于用计算值替换matplotlib刻度标签的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆