Matplotlib pyplot轴格式化程序

时间:2014-08-04 12:55:23

标签: python matplotlib axes ticker

我有一张图片:

enter image description here

在y轴上,我想获得5x10^-5 4x10^-5等等而不是0.00005 0.00004

到目前为止我尝试的是:

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

这似乎不起作用。代码的document page似乎没有提供直接的答案。

1 个答案:

答案 0 :(得分:10)

您可以使用matplotlib.ticker.FuncFormatter通过功能选择刻度线的格式,如下面的示例代码所示。实际上,所有功能都是将输入(浮点数)转换为指数表示法,然后替换&#39; e&#39;与&#39; x10 ^&#39;所以你得到你想要的格式。

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

image

如果您愿意使用指数表示法(即5.0e-6.0),那么有一个更整洁的解决方案,您可以使用matplotlib.ticker.FormatStrFormatter选择格式字符串,如下所示。字符串格式由标准Python字符串格式规则给出。

...

y_fmt = tick.FormatStrFormatter('%2.2e')
ax.yaxis.set_major_formatter(y_fmt)

...
相关问题