数字1.67845714e-12是我的物理项目的重要结果。我想绘制图形,其中y轴极限围绕此结果作为比例因子。
在下面的示例中:
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
import random
x = np.arange(0,100)
y = np.zeros(len(x))
for i in range(len(x)):
y[i] = 1.67845714e-12*random.random() - (4.20e-14)*x[i]
plt.ylim(float(-3*1.67845714e-12), float(3*1.67845714e-12)) #The important line
plt.plot(x,y)
所得的plot的y轴从-5*e-12
到5*e-12
,而不是y轴从-3*1.67845714e-12
到3*1.67845714e-12
如何使Matplotlib像我想要的那样以-3到3的比例显示1.67845714e-12
的比例因子?并且,如果由于例如数字太长而无法这样做,是否可以给我的数字起昵称(例如“结果”),并使matplotlib将其用作缩放比例?]
我尝试使用其他命令,例如ax.set_yticks()
,ax=plt.gta()
或ax.set_ylim()
,但我搜索过的所有内容似乎都无效。
我正在尝试根据我的理解来回答你想做的事情。正如我所看到的,您希望有一个从y
到-3*1.67845714e-12
的3*1.67845714e-12
轴,但每个步/刻度的大小都是1.67845714e-12
。
注意,我创建了一个名为scalingFactor
的变量来保存1.67845714e-12
。我认为这回答了您的问题之一。然后,您可以使用它而不是写完整的数字。
确定,生成刻度,因此您可以使用numpy.arange(inf, sup, step)
功能。它返回给定间隔[inf;sup)
中的均匀间隔的值。因此,我们将使用-3*scalingFactor
步骤生成从3*scalingFactor
到1.67845714e-12
的价格变动。您可能会在代码中注意到sup=4*scalingFactor
。这是因为numpy.arange()
排除了间隔的上限。
要获得轴上的整数而不是四舍五入,您可以使用plt.gca().yaxis.set_major_formatter(mtick.FormatStrFormatter('%.8e'))
强制其具有8个小数位。此函数格式化轴刻度的标签,在这种情况下,它使用此字符串格式%.8e
。
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
import random
import matplotlib.ticker as mtick
x = np.arange(0,100)
y = np.zeros(len(x))
scalingFactor = 1.67845714e-12
for i in range(len(x)):
y[i] = scalingFactor*random.random() - (4.20e-14)*x[i]
inf = -3*scalingFactor
sup = 4*scalingFactor
plt.plot(x, y)
plt.ylim(inf, sup)
plt.yticks(np.arange(inf, sup, scalingFactor))
plt.subplots_adjust(left=0.24) # Squash the plot from the left so the ticks labels can be seen
plt.gca().yaxis.set_major_formatter(mtick.FormatStrFormatter('%.8e'))
plt.show()
输出
希望这会有所帮助。