import matplotlib.ticker as ticker
import numpy as np
ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda y,pos: ('{{:.{:1d}f}}'.format(int(np.maximum(-np.log10(y),0)))).format(y)))
为了清楚起见,这里的lambda函数以更详细但也更容易理解的方式写出:
def myLogFormat(y,pos):
# Find the number of decimal places required
decimalplaces = int(np.maximum(-np.log10(y),0)) # =0 for numbers >=1
# Insert that number into a format string
formatstring = '{{:.{:1d}f}}'.format(decimalplaces)
# Return the formatted tick label
return formatstring.format(y)
ax.yaxis.set_major_formatter(ticker.FuncFormatter(myLogFormat))
我发现Joe's和Tom's答案非常有用,但是在对这些答案的评论中有很多有用的细节。以下是两种情况的摘要:
范围大于1
下面是类似于Joe的示例代码,但范围更大:
用科学符号表示这样的情节:
在乔的回答中,我使用
ScalarFormatter
,但我也调用set_scientific(False)
。当规模达到或超过1000000时,这是必要的。低于1的范围
在汤姆的回答中,当范围小于1时,会发生以下情况:
它将x轴上的前两个刻度显示为零。
切换到
FuncFormatter
可以处理这个问题。同样,我对1000000或更高的数字也有问题,但是给格式字符串添加一个精度就解决了这个问题。我发现,如果所有的tick值都大于或等于1,那么使用
ScalarFormatter
非常好。但是,如果您在数字<1
处有一个勾号,ScalarFormatter
会将勾号标签打印为0
。我们可以使用matplotlib^{} 模块中的^{} 来解决此问题。最简单的方法是使用
lambda
函数和g
格式说明符(感谢注释中的@lenz)。注意在我最初的回答中,我没有使用
g
格式,而是使用了这个lambda
函数和FuncFormatter
来将数字>= 1
设置为其整数值,将数字<1
设置为其十进制值,并要求最小的小数位数(即0.1, 0.01, 0.001
,等等)。它假设您只是在base10
值上设置勾号。为了清楚起见,这里的lambda函数以更详细但也更容易理解的方式写出:
当然,只要改变格式化程序。
例如,如果我们有这个情节:
您可以手动设置刻度标签,但当您缩放/平移/等时,刻度位置和标签将被固定。因此,最好更改格式化程序。默认情况下,对数刻度使用
LogFormatter
,这将以科学记数法格式化值。要将格式化程序更改为线性轴(ScalarFormatter
)的默认值,请使用例如相关问题 更多 >
编程相关推荐