Python Matplotlib pyplot 轴格式化程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25119193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matplotlib pyplot axes formatter
提问by user3397243
I have an image:
我有一个图像:


Here in the y-axis I would like to get 5x10^-5 4x10^-5and so on instead of 0.00005 0.00004.
在 y 轴上,我想得到5x10^-5 4x10^-5等等而不是0.00005 0.00004.
What I have tried so far is:
到目前为止我尝试过的是:
fig = plt.figure()
ax = fig.add_subplot(111)
y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=True)
ax.yaxis.set_major_formatter(y_formatter)
ax.plot(m_plot,densities1,'-ro',label='0.0<z<0.5')
ax.plot(m_plot,densities2, '-bo',label='0.5<z<1.0')
ax.legend(loc='best',scatterpoints=1)
plt.legend()
plt.show()
This does not seem to work. The document pagefor tickers does not seem to provide a direct answer.
这似乎不起作用。股票代码的文档页面似乎没有提供直接的答案。
采纳答案by Ffisegydd
You can use matplotlib.ticker.FuncFormatterto choose the format of your ticks with a function as shown in the example code below. Effectively all the function is doing is converting the input (a float) into exponential notation and then replacing the 'e' with 'x10^' so you get the format that you want.
您可以使用matplotlib.ticker.FuncFormatter以下示例代码中所示的函数来选择报价的格式。实际上,所有函数所做的都是将输入(浮点数)转换为指数符号,然后将 'e' 替换为 'x10^',这样您就可以获得所需的格式。
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
import numpy as np
x = np.linspace(0, 10, 1000)
y = 0.000001*np.sin(10*x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
def y_fmt(x, y):
return '{:2.2e}'.format(x).replace('e', 'x10^')
ax.yaxis.set_major_formatter(tick.FuncFormatter(y_fmt))
plt.show()


If you're willing to use exponential notation (i.e. 5.0e-6.0) however then there is a much tidier solution where you use matplotlib.ticker.FormatStrFormatterto choose a format string as shown below. The string format is given by the standard Python string formatting rules.
如果您愿意使用指数表示法(即 5.0e-6.0),那么有一个更整洁的解决方案,您可以使用它matplotlib.ticker.FormatStrFormatter来选择如下所示的格式字符串。字符串格式由标准 Python 字符串格式规则给出。
...
y_fmt = tick.FormatStrFormatter('%2.2e')
ax.yaxis.set_major_formatter(y_fmt)
...

