Pandas groupby object in legend on plot
<p>I am trying to plot a pandas <code>groupby</code> object using the code <code>fil.groupby('imei').plot(x=['time'],y = ['battery'],ax=ax, title = str(i))</code> </p>

<p>The problem is the plot legend lists <code>['battery']</code>as the legend value. Given it's drawing a line for each item in the <code>groupby</code> object, it makes more sense to plot those values in the legend instead. However I'm not sure how to do that. Any help would be appreciated.</p>

<p>Data</p>

<pre><code>                 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
</code></pre>

<p>Full code </p>

<pre><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()
</code></pre>

<p>Current plot </p>

<p><a href="http://i.stack.imgur.com/rDNvf.png" rel="nofollow"><img src="http://i.stack.imgur.com/rDNvf.png" alt="enter image description here"></a></p>

<p>Slightly tidied data:</p>

<pre><code>    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
</code></pre>

<p>Complete example code:</p>

<pre><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()
</code></pre>

<p>The x-values have to be converted to datetime for plotting to come out right, as usual. You could do that in the dataframe, too. </p>

<p>Result, labeled by imei:</p>

<p><a href="http://i.stack.imgur.com/wHM4b.png" rel="nofollow"><img src="http://i.stack.imgur.com/wHM4b.png" alt="enter image description here"></a>
(NOTE: edited to get rid of an oddity I tripped over the first time. If you pass a list as the <code>y</code> argument to <code>group.plot</code>, the list IDs will be used as the line labels, presumably as a handy default for when you're plotting several dependent variables at once.</p>

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

<p>)</p>

python pandas matplotlib plot