Matplotlib pyplot轴格式化程序

use*_*243 8 python axes matplotlib ticker

我有一张图片:

在此输入图像描述

在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() 
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用.代码的文档页面似乎没有提供直接的答案.

Ffi*_*ydd 10

您可以使用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()
Run Code Online (Sandbox Code Playgroud)

图片

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

...

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

...
Run Code Online (Sandbox Code Playgroud)

  • `%2.2e`选择你希望你的字符串所在的格式.数字现在选择你想要的许多小数位,e选择科学记数法.您可以在此处找到更多详细信息(https://docs.python.org/2/library/stdtypes.html#string-formatting). (4认同)
  • 你的简短解决方案中的`%2.2e`有什么作用? (2认同)
  • 如果我有 1000、2000、...10000,你知道我如何将它们显示为 1K、2K、10K? (2认同)