【问题标题】:How do I set an exact float as the scaling factor for my y-axis limits on Matplotlib?如何设置一个精确的浮点数作为 Matplotlib 上 y 轴限制的比例因子?
【发布时间】:2020-03-25 19:53:44
【问题描述】:

数字 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-125*e-12 ,而不是从 -3*1.67845714e-123*1.67845714e-12 的 y 轴

我怎样才能让 Matplotlib 在图表的左上角显示1.67845714e-12 的步骤,并且像我想要的那样在 y 轴上显示 -3 到 3 的比例?如果这不可能,例如步骤太长,我可以给我的步骤一个昵称(例如“结果”)来完成这项工作吗?

我尝试过使用其他命令,例如 ax.set_yticks()ax=plt.gta()ax.set_ylim() 但我搜索过的东西似乎都不起作用。

【问题讨论】:

  • 您能否详细说明或尝试给出一个期望输出示例,因为我不完全理解您想要什么。此外,您应该知道,如果您将 y 限制从 -3 设置为 3,您将无法看到绘制数据的详细信息。
  • 已编辑帖子,希望现在更清楚!
  • 我编辑了我的答案以反映您的解释。希望对您有所帮助。

标签: python matplotlib scaling


【解决方案1】:

我正在尝试根据我理解您想要做的事情来回答。正如我所看到的,您希望有一个从-3*1.67845714e-123*1.67845714e-12y 轴,但每个步骤/刻度的大小都是1.67845714e-12

注意我创建了一个名为scalingFactor 的变量来保存1.67845714e-12。我认为这回答了你的一个问题。然后你可以使用它而不是写整数。

好的,生成刻度以便您可以使用numpy.arange(inf, sup, step) 函数。它返回给定间隔[inf;sup) 内的均匀间隔值。所以我们将使用1.67845714e-12 步骤生成从-3*scalingFactor3*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

有一些格式化程序类可以格式化刻度值和处理偏移值(左上角的刻度值)。所以我们可以创建一个继承自ScalarFormatterModScalarFormatter,并重写一些函数来手动设置我们想要的偏移量和刻度,而不需要让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()

输出:

注意:我很确定应该有一种更优雅的方式来实现这一点,但这是我为您的特定问题提供帮助和临时解决方案的方式。

希望这会有所帮助。

【讨论】:

  • 您需要调用plt.ylim调用plt.plot
  • 替代 y 刻度标签:plt.yticks(np.linspace(-3 * 1.67845714e-12, 3 * 1.67845714e-12, 7), [f'{i}*Result' for i in range(-3, 4)])
  • @JohanC。哎呀,你是对的,已经编辑了它。此外,您的其他 cmets 似乎也很完美,尽管我使用的是 python3.5f{} 在那里不起作用。但这是一种完美有效的方法。我什至会说它更干净......
  • 非常感谢!是否可以将比例因子显示在左上角,仅在 y 轴上显示数字 -3、-2、-1、0、1、2、3?模仿matplotlib默认绘制图形的方式?
  • 澄清一下,是否可以在图形的左上角仅显示-3、-2、-1、0、1、2、3的步长1.67845714e-12缩放显示在 y 轴上? (这是 matplotlib 默认的绘图方式)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
  • 2021-01-13
相关资源
最近更新 更多