Matplotlib pyplot轴窗体

2024-04-19 13:11:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个形象:

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似乎没有提供直接的答案。


Tags: addplotmatplotlibformatterfigpltaxlabel
1条回答
网友
1楼 · 发布于 2024-04-19 13:11:31

您可以使用^{}使用下面的示例代码所示的函数来选择记号的格式。实际上,该函数所做的全部工作就是将输入(浮点)转换为指数表示法,然后将“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()

image

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

...

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

...

相关问题 更多 >