Skip to content Skip to sidebar Skip to footer

How To Plot Several Line Charts In One Figure (overlay/groupby)

I would like to illustrate the change in one variable for several persons in my data over time. I have several issues with basic commands here. Here is my data: import pandas as p

Solution 1:

You can also use either groupby:

df.set_index('year').groupby('id').money.plot()

which gives:

enter image description here

or, use seaborn with hue

sns.lineplot(x='year',y='money', hue='id', data=df)

which gives:

enter image description here


Solution 2:

Since you have tagged matplotlib, one solution is to check for the id while looping through the DataFrame before plotting using df[df['id']==i].

To overlay those plots in one figure, create a figure object and pass the axis ax to the df.plot() function.

import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'year': ['1988', '1989', '1990', '1988', '1989', '1990', '1988', '1989', '1990'],
                   'id': ['1', '1', '1', '2', '2', '2', '3', '3', '3'],
                   'money': ['5', '7', '8', '8', '3', '3', '7', '8', '10']}).astype(int)

fig, ax = plt.subplots()

for i in df.id.unique():
    df[df['id']==i].plot.line(x='year', y='money', ax=ax, label='id = %s'%i)
plt.xticks(np.unique(df.year),rotation=45)    

enter image description here

Pandas solution using groupby would look like following. Here you will have to modify the legends later.

df.groupby('id').plot(x='year', y='money',legend=True, ax=ax)

h,l = ax.get_legend_handles_labels()
ax.legend(h, df.id.unique(), fontsize=12)
plt.xticks(np.unique(df.year), rotation=45)

Solution 3:

Can also be done with a simple pivot

df.pivot(index='year', columns='id', values='money').plot(rot=45)

enter image description here

If some entries are missing years, then this will not plot perfectly, so add an interpolation:

(df.pivot(index='year', columns='id', values='money')
   .apply(pd.Series.interpolate, limit_area='inside')
   .plot())

Post a Comment for "How To Plot Several Line Charts In One Figure (overlay/groupby)"