MemoryError 与 numpy arange

MemoryError with numpy arange

我想创建一个 10 的幂数组作为绘图 y 轴的标签。 我将 plt.yticks() 与导入为 plt 的 matplotlib 一起使用,但这在这里并不重要。 我有一些图,其中 y 轴从 1e3 到 1e15 不等。这些是对数图。 Matplotlib 会自动显示带有 1e2 步长刻度的刻度,而我希望步长为 10(以便能够正确使用小刻度)。

我想按上述使用 plt.yticks(numpy.arange(1e3, 1e15, 10)) 命令,但 numpy.arange(1e3, 1e15, 10) 导致内存错误。它不是应该输出一个长度为 13 的数组吗?为什么内存变满了?

如何绕过这个问题而不是手动构建数组?

我也尝试过使用内置 range,但它不适用于浮点数。

谢谢。

试试 NumPy 中的 logspace 作为

plt.yticks(numpy.logspace(3, 15, 13))

在这里你给出起始和最后的指数(10 的幂)以及它们之间的数据点数。如果你打印上面的网格,你会得到以下内容

array([1.e+03, 1.e+04, 1.e+05, 1.e+06, 1.e+07, 1.e+08, 1.e+09, 1.e+10,
   1.e+11, 1.e+12, 1.e+13, 1.e+14, 1.e+15])

在这种情况下,numpy 中的函数 logspace 更合适。 这个例子的答案是 np.logspace(3,15,num=15-3+1, endpoint=True)

你也可以这样做:

10. ** np.arange(3,16)

小数点很重要,因为没有它你会溢出默认的 int32 整数数据类型

另一种方法是使用 LogLocator from the matplotlib.ticker 模块,并手动增加刻度数(默认情况下,它会尝试设置一个很好的 -查看刻度数;也就是说,它看起来不会太拥挤)。

在这个例子中,我将右侧 Axes 的刻度数设置为 13(使用 numticks=13),你可以看到这增加了刻度数,所以有一个在 10 的每个整数次幂上。

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

# Create figure and axes
fig, (ax1, ax2) = plt.subplots(ncols=2)

# Make yscale logarithmic
ax1.set_yscale('log')
ax2.set_yscale('log')

# Set y limits
ax1.set_ylim(1e3, 1e15)
ax2.set_ylim(1e3, 1e15)

# On ax2, lets tell the locator how many ticks we want
ax2.yaxis.set_major_locator(ticker.LogLocator(numticks=13))

ax1.set_title('default ticks')
ax2.set_title('LogLocator with numticks=13')

plt.show()

编辑:

要使用此方法添加次要刻度,我们可以使用另一个 LogLocator,这次设置 subs 选项来说明我们希望在每个十年中的何处进行次要刻度。在这里,我没有在每个 0.1 上设置小刻度,因为它太局促了,所以只为一个子集完成。请注意,如果您像这样设置次要刻度,您还需要使用 NullFormatter 关闭次要刻度的刻度标签。

ax2.yaxis.set_major_locator(ticker.LogLocator(numticks=13))
ax2.yaxis.set_minor_locator(ticker.LogLocator(subs=(0.2,0.4,0.6,0.8),numticks=13))
ax2.yaxis.set_minor_formatter(ticker.NullFormatter())