Pandas groupby object in the legend on the plot

I am trying to build a pandas groupby object using the code fil.groupby('imei').plot(x=['time'],y = ['battery'],ax=ax, title = str(i))

The problem is that the list of plot legends ['battery'] is the legend value. Given that it draws a line for each element in the groupby object, it makes sense to display these values ​​in a legend. However, I am not sure how to do this. Any help would be appreciated.

Data

  time imei battery_raw 0 2016-09-30 07:01:23 862117020146766 42208 1 2016-09-30 07:06:23 862117024146766 42213 2 2016-09-30 07:11:23 862117056146766 42151 3 2016-09-30 07:16:23 862117995146745 42263 4 2016-09-30 07:21:23 862117020146732 42293 

Full code

 for i in entity: fil = df[(df['entity_id']==i)] fig, ax = plt.subplots(figsize=(18,6)) fil.groupby('imei').plot(x=['time'],y = ['battery'],ax=ax, title = str(i)) plt.legend(fil.imei) plt.show() 

Current plot

enter image description here

+6
source share
1 answer

A few data:

  date time imei battery_raw 0 2016-09-30 07:01:23 862117020146766 42208 1 2016-09-30 07:06:23 862117020146766 42213 2 2016-09-30 07:11:23 862117020146766 42151 3 2016-09-30 07:16:23 862117995146745 42263 4 2016-09-30 07:21:23 862117995146745 42293 

Full Code Code:

 import matplotlib.pyplot as plt fil = pd.read_csv('imei.csv', sep=r'\s*', engine='python') fig, ax = plt.subplots(figsize=(18,6)) for name, group in fil.groupby('imei'): group.plot(x=pd.to_datetime(group['time']), y='battery_raw', ax=ax, label=name) plt.show() 

The x values ​​must be converted to datetime to plot, as usual. You can do this in a data frame.

Result tagged imei:

enter image description here (NOTE: edited to get rid of the strangeness I was working with for the first time. If you pass the list as the y argument to group.plot , the list identifiers will be used as line labels, presumably as a convenient default value for when you draw several dependent variables at once.

 #for name, group in fil.groupby('imei'): # group.plot(x=['time'], y=['battery_raw'], ax=ax, label=name) 

)

+7
source

All Articles