npm
npm

Reputation: 653

How to separately plot and save to figure from multiple files using glob and matplotlib?

I tried to plot multiple files then save it separately with this code:

import pandas as pd
import matplotlib.pyplot as plt


filenames = sorted(glob.glob('./CSV/*.csv'))
for f in filenames:
    print(f)
    df = pd.read_csv(f, delimiter=',')

    plt.plot(df['Date'], df['step'], color="orange")
    plt.xticks(rotation='vertical')
    plt.xlabel('Date and time')
    plt.ylabel('No. of steps')
    plt.grid(True)

    plt.savefig(f'{f[:-10]}-.jpg', bbox_inches='tight')

But the result will be several plot in one png/jpg file. For example from 3 files:

enter image description here

What should I add to make separate plot and save each plot as several files?

Upvotes: 1

Views: 233

Answers (1)

Polkaguy6000
Polkaguy6000

Reputation: 1208

After plt.savefig... add a line with plt.close(). This will close the current plot and give a blank slate for when you start the next plot.

Upvotes: 1

Related Questions