I'm looking to create a line graph with the y axis having multiple lines for each unique entry found within my dataframe column.
My dataframe looks like this –
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'command': ['start', 'start', 'hold',
'release', 'hold', 'start',
'hold', 'hold', 'hold'],
'name': ['fred', 'wilma', 'barney',
'fred', 'barney', 'betty',
'pebbles', 'dino', 'wilma'],
'date': ['2020-05', '2020-05', '2020-05',
'2020-06', '2020-06', '2020-06',
'2020-07', '2020-07', '2020-07']})
I'm trying to create a line graph with the X axis as the date, and the y axis would have a separate line for each of the command entries(start, hold, & release in this example).
I tried using a groupby then executing this –
dfg = df.groupby(['command', 'date']).size()
for i in dfg.command.unique():
x = dfg[dfg.command==i]['date']
y = dfg[dfg.command==i]['size']
plt.plot(x, y)
plt.show()
However I get this error - AttributeError: 'Series' object has no attribute 'command'
I've also tried creating a pivot table and building the graph from there as follows -
df_pv = pd.pivot_table(df, index=['command', 'date'],
values='name',
aggfunc='count')
df_pv.rename(columns={'name': 'count'}, inplace=True)
for i in df_pv.command.unique():
x = df_pv[df_pv.command==i]['date']
y = df_pv[df_pv.command==i]['count']
plt.plot(x, y)
plt.show()
However it returns the error - AttributeError: 'DataFrame' object has no attribute 'command'
I'm not sure if I'm missing something in my approach?
Or if there is a better method of achieving this?
Thanks.