Search code examples
pythontime-seriesgeneratorsave-image

How to save generator object to png, jpg or other image files


I'm using timeseries-generator from GitHub to get synthetic line graphs.

That works good.

But now I want to save the plots into a file as sepparate png-images.

This is my code so far:

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)))

The last line get me following error: AttributeError: 'Generator' object has no attribute 'savefig'

The type of object g is:

print(type(g))

<class 'timeseries_generator.generator.Generator'>

I tried following suggestion from an other post: Save image from generator object:

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

But that doesn't work for me. Maybe I'm using it wrong, with:

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

I get following error: TypeError: a bytes-like object is required, not 'Generator'

Is there a way to change the generator object into something else to save the images or is there a way to save the generator objects as png? Or can I use the suggestion above, but do it wrong?

Thank you for your help in advance!


Solution

  • g.plot() simply calls the plot() method of the underlying Pandas dataframe. You should get the dataframe and export it on your own:

    fig = g.ts.plot(kind='line', figsize=(20, 16)).get_figure()
    fig.savefig(path.join(outpath,"graph_{0}.png".format(element)))