Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot a time series with this dataframe?

I want to plot this dataframe like a time series, a line for every country that every year increases or decreases according to 'count'. How can i do this?

        country  count
Year            
2005    Australia   2
2005    Austria     1
2005    Belgium     0
2005    Canada      4
2005    China       0
2006    Australia   3
2006    Austria     0
2006    Belgium     1
2006    Canada      5
2006    China       2
2007    Australia   5
2007    Austria     1
2007    Belgium     2
2007    Canada      6
2007    China       3

I'd like a thing like this: enter image description here

like image 257
SimoneA Avatar asked Sep 06 '25 03:09

SimoneA


2 Answers

You can use pd.pivot_table and df.plot for this:

df.pivot_table(index='Year', columns='country', values='count').plot(xticks=df.Year.unique())

Will return

enter image description here

like image 87
T C Molenaar Avatar answered Sep 07 '25 17:09

T C Molenaar


You can use seaborn.lineplot:

import seaborn as sns

df.Year = pd.to_datetime(df.Year)

sns.set(rc={'figure.figsize':(12, 8)}) # changed the figure size to avoid overlapping
sns.lineplot(data=df, x=df['Year'].dt.strftime('%Y'), # show only years with strftime
             y=df['count'], hue='country') 

which givesenter image description here

like image 44
Nuri Taş Avatar answered Sep 07 '25 15:09

Nuri Taş