如何将生成器对象保存为png、jpg或其他图像文件

问题描述 投票:0回答:1

我正在使用 GitHub 上的 timeseries-generator 来获取合成线图。

效果很好。

但现在我想将绘图作为单独的 png 图像保存到文件中。

这是我到目前为止的代码:

i=range(0,4) #first number inclusive, second exclusive

for element in i:
    outpath = "PATH"
    c=random.random()
    o=random.random()
    s=random.random()
    lt = LinearTrend(coef=c, offset=o, col_name="plot no. {0}".format(element))
    g = Generator(factors={lt}, features=None, date_range=pd.date_range(start="01-01-2020", end="12-31-2020"))
    wn = WhiteNoise(stdev_factor=s)
    g.update_factor(wn)
    g.generate()
    g.plot()
    g.savefig(path.join(outpath,"graph_{0}.png".format(element)))

最后一行出现以下错误:

AttributeError: 'Generator' object has no attribute 'savefig'

对象

g
的类型是:

print(type(g))

<class 'timeseries_generator.generator.Generator'>

我尝试遵循其他帖子的建议: 从生成器对象保存图像:

with open("output_file.png", "wb") as fp:
    for chunk in thumb_local:
        fp.write(chunk)

但这对我不起作用。 也许我用错了,用:

with open("graph_{0}.png".format(element), "wb") as fp:
        fp.write(g)

我收到以下错误:

TypeError: a bytes-like object is required, not 'Generator'

有没有办法将生成器对象更改为其他对象来保存图像,或者有没有办法将生成器对象保存为 png? 或者我可以使用上面的建议,但做错了?

提前感谢您的帮助!

python time-series generator save-image
1个回答
0
投票

g.plot()
只需调用底层 Pandas 数据帧的
plot()
方法。您应该获取数据框并自行导出:

fig = g.ts.plot(kind='line', figsize=(20, 16)).get_figure()
fig.savefig(path.join(outpath,"graph_{0}.png".format(element)))
© www.soinside.com 2019 - 2024. All rights reserved.