简体   繁体   English

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

[英]Simplify scientific notation/offset in matplotlib axis

I am trying to draw a plot with large data using matplotlib. matplotlib simplifies the numbers on the y-axis which is expected.我正在尝试使用 matplotlib 绘制带有大数据的 plot。matplotlib 简化了预期的 y 轴上的数字。 However, there are too many useless leading zeros that I can not find a way to remove.但是,有太多无用的前导零,我找不到删除的方法。

Here's a reproducible example:这是一个可重现的例子:

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

What I get looks like this:我得到的是这样的:

在此处输入图像描述

I know how to disable useOffset but I want the top of the y-axis to keep the scientific notation and just say 1e11+1.04e16 instead of 1e11+1.0400000000e16 .我知道如何禁用 useOffset 但我希望 y 轴的顶部保留科学记数法,只说1e11+1.04e16而不是1e11+1.0400000000e16 Any ideas on how to solve this?关于如何解决这个问题的任何想法?

For this you can easily do that by matplotlib.ticker module.为此,您可以通过matplotlib.ticker模块轻松做到这一点。 All you have to do is add this code snippet to your code,您所要做的就是将此代码片段添加到您的代码中,

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

This code will produce the result in scientific form.此代码将以科学形式产生结果。 That is it will show x10^11+1.04*10^16也就是说它会显示x10^11+1.04*10^16

And if you are specific with your desired output try the code below,如果您特定于所需的 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()

The second code uses annotate method.第二个代码使用annotate方法。 So the arguments to be passed are the text to be displayed in the desired format and the second argument specifies the x and y coordinates.因此,要传递的 arguments 是以所需格式显示的文本,第二个参数指定 x 和 y 坐标。 Hope this helps!希望这可以帮助!

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

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