Home > Enterprise >  Produce time series plots for each name pandas
Produce time series plots for each name pandas

Time:07-07

I have a Pandas data frame df that looks like this:

       date                 A      B        name
 2022-06-25 04:00:00       700     532        aa
 2022-06-25 05:00:00      1100     433        aa
 2022-06-25 06:00:00       800     754        aa
 2022-06-25 07:00:00      1200     288        aa
 2022-06-25 08:00:00       700     643        bb
 2022-06-25 09:00:00      1400     668        bb
 2022-06-25 10:00:00      1600     286        bb
                     .....
 2022-06-03 11:00:00       397      46        cc
 2022-06-03 12:00:00       100       7        cc
 2022-06-03 13:00:00       400      25        cc
 2022-06-03 14:00:00       500      41        cc
 2022-06-03 15:00:00       400       0        cc
 2022-06-03 16:00:00       300      23        dd
 2022-06-03 17:00:00       500      50        dd
 2022-06-03 18:00:00       300       0        dd
 2022-06-03 19:00:00       400      15        dd

I'm trying to Produce time series plots for each name. Line charts.
number of daily A vs date
number of daily B vs date

I was able to do so and get a plot for each name like this:

df.groupby('name').plot(x='date', figsize=(24,12))

But I couldn't specify a title for each plot like this plt.title(" ") And also couldn't auto save each plot like this plt.savefig('name.png') Because they all produce at once.

Is there any other way to produce plots so I can specify the title and save each plot automatically?

Thank you

CodePudding user response:

One of the ways to do what you require is to put the code for your plot creation and plot save inside a for loop. That will allow you to add a title using the title. Also, you will be able to use savefig to individually save each of the plots. The update code and one of the output graphs is shown below. Note that I am adding name as the title and saving the figure as Myplot <name>.png

for name, group in df.groupby('name'):
    group.plot(x='date', title=name)
    plt.savefig('Myplot {}.png'.format(name), bbox_inches='tight')

First plot

enter image description here

  • Related