gpt4 book ai didi

python - 大型 PyPlot - 避免内存分配

转载 作者:行者123 更新时间:2023-11-30 23:53:27 27 4
gpt4 key购买 nike

我正在做一个相当大的 PyPlot (Python matplotlib) (600000 个值,每个 32 位)。实际上我想我可以简单地做这样的事情:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])

两个数组,都在内存中分配。不过,我迟早必须绘制文件,其中包含数千兆字节的信息。

如何避免将两个数组传递到 plt.plot() 中?

但是我仍然需要一个完整的情节。因此,我认为仅使用迭代器并逐行传递值是不可能完成的。

最佳答案

如果您谈论的是千兆字节的数据,您可能会考虑批量加载和绘制数据点,然后将每个渲染图的图像数据分层到前一个图上。这是一个简单的示例,内嵌注释:

import Image
import matplotlib.pyplot as plt
import numpy

N = 20
size = 4
x_data = y_data = range(N)

fig = plt.figure()

prev = None
for n in range(0, N, size):
# clear figure
plt.clf()

# set axes background transparent for plots n > 0
if n:
fig.patch.set_alpha(0.0)
axes = plt.axes()
axes.patch.set_alpha(0.0)

plt.axis([0, N, 0, N])

# here you'd read the next x/y values from disk into memory and plot
# them. simulated by grabbing batches from the arrays.
x = x_data[n:n+size]
y = y_data[n:n+size]
ax = plt.plot(x, y, 'ro')
del x, y

# render the points
plt.draw()

# now composite the current image over the previous image
w, h = fig.canvas.get_width_height()
buf = numpy.fromstring(fig.canvas.tostring_argb(), dtype=numpy.uint8)
buf.shape = (w, h, 4)
# roll alpha channel to create RGBA
buf = numpy.roll(buf, 3, axis=2)
w, h, _ = buf.shape
img = Image.fromstring("RGBA", (w, h), buf.tostring())
if prev:
# overlay current plot on previous one
prev.paste(img)
del prev
prev = img

# save the final image
prev.save('plot.png')

输出:

enter image description here

关于python - 大型 PyPlot - 避免内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5673934/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com