Home > Enterprise >  How to plot a time series with this dataframe?
How to plot a time series with this dataframe?

Time:09-23

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

CodePudding user response:

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

CodePudding user response:

A pure pandas solution would be using pivot

df = pd.DataFrame({'Year':[2005,2005,2005,2005,2005,
                        2006,2006,2006,2006,2006,
                       2007,2007,2007,2007,2007],
                 'country' : ['Australia', 'Austria','Belgium', 'Canada', 'China']*3,
                 'count':[2,1,0,4,0,3,0,1,5,2,5,1,2,6,3]})

df.pivot(index='Year', columns='country').plot()

CodePudding user response:

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

Will return enter image description here

  • Related