我正在尝试根据我理解您想要做的事情来回答。正如我所看到的,您希望有一个从-3*1.67845714e-12 到3*1.67845714e-12 的y 轴,但每个步骤/刻度的大小都是1.67845714e-12。
注意我创建了一个名为scalingFactor 的变量来保存1.67845714e-12。我认为这回答了你的一个问题。然后你可以使用它而不是写整数。
好的,生成刻度以便您可以使用numpy.arange(inf, sup, step) 函数。它返回给定间隔[inf;sup) 内的均匀间隔值。所以我们将使用1.67845714e-12 步骤生成从-3*scalingFactor 到3*scalingFactor 的刻度。您可能会在代码中注意到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()
输出
编辑:
好吧,事实上,我一直在为你想要的东西而苦苦挣扎,因为我从来不需要那样做。但是,我根据您的需要为您的问题提出了一个非常临时的解决方案,因为您的所有数据似乎都在该范围内,并且您希望缩放因子为 1.67845714e-12。
有一些格式化程序类可以格式化刻度值和处理偏移值(左上角的刻度值)。所以我们可以创建一个继承自ScalarFormatter 的ModScalarFormatter,并重写一些函数来手动设置我们想要的偏移量和刻度,而不需要让matplotlib 计算它:
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
import random
import math
import matplotlib.ticker as mtick
class ModScalarFormatter(mtick.ScalarFormatter):
def __init__(self, useOffset=None, useMathText=None, useLocale=None):
mtick.ScalarFormatter.__init__(self, useOffset, useMathText, useLocale)
# Create the ticks we want
self.ticks = [i for i in range(-3, 4)]
def _set_offset(self, text):
self.offset = text # Set the offset text we want
def get_offset(self, txt=''):
return self.offset # Return the offset value
def __call__(self, x, pos=None):
# The __call__ returns the tick on position `pos` from the
# ticks we specified
return self.ticks[pos]
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 = 3*scalingFactor
plt.plot(x, y)
plt.yticks(np.linspace(inf, sup, 7))
# Create and use a Custom Scalar Formatter Class
sf = ModScalarFormatter(useOffset=1.67845714e-12)
plt.gca().yaxis.set_major_formatter(sf)
plt.ylim(inf, sup)
plt.show()
输出:
注意:我很确定应该有一种更优雅的方式来实现这一点,但这是我为您的特定问题提供帮助和临时解决方案的方式。
希望这会有所帮助。