繁体   English   中英

简化matplotlib轴中的科学记数法/偏移量

[英]Simplify scientific notation/offset in matplotlib axis

我正在尝试使用 matplotlib 绘制带有大数据的 plot。matplotlib 简化了预期的 y 轴上的数字。 但是,有太多无用的前导零,我找不到删除的方法。

这是一个可重现的例子:

import matplotlib.pyplot as plt
y = [i for i in range(10400000000000000, 10400750000000000,500000000000)]
x = [i for i in range(len(y))]
plt.plot(x,y)
plt.show()

我得到的是这样的:

在此处输入图像描述

我知道如何禁用 useOffset 但我希望 y 轴的顶部保留科学记数法,只说1e11+1.04e16而不是1e11+1.0400000000e16 关于如何解决这个问题的任何想法?

为此,您可以通过matplotlib.ticker模块轻松做到这一点。 您所要做的就是将此代码片段添加到您的代码中,

import matplotlib.ticker as ticker

fig, ax = plt.subplots
ax.plot(x, y)
# Initializing the formatter
formatter = ticker.ScalarFormatter(useMathText = True)
formatter.set_scientific(True)
formatter.set_powerlimits((-1, 1))
ax.yaxis.set_major_formatter(formatter)

# And finally plotting our graph
plt.show()

此代码将以科学形式产生结果。 也就是说它会显示x10^11+1.04*10^16

如果您特定于所需的 output,请尝试以下代码,

import matplotlib.pyplot as plt

y = [i for i in range(10400000000000000, 10400750000000000,500000000000)]
x = [i for i in range(len(y))]

fig, ax = plt.subplots()
ax.plot(x, y)

ax.annotate("1e11+1.04e16", (x[-1], y[-1]), xytext=(x[-1]-100, y[-1]+1000000000), arrowprops=dict(facecolor='red', shrink=0.05))

plt.show()

第二个代码使用annotate方法。 因此,要传递的 arguments 是以所需格式显示的文本,第二个参数指定 x 和 y 坐标。 希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM