What do I need to do using IPython and ggplot to get legends on multiple time series plots?
I am trying to find out how to use the ggplot library in python. In looking at some examples, I noticed that time series of several series seem to need
pandas.melt()
data in long form.
Usage Is there a way to plot pandas series in ggplot? as a model, I am playing with a meat dataset in ggplot. While the data display appears to be fine, there is no legend. The recipe for fixing the legend at the bottom of the link fails in my example.
I saw a message somewhere that says that displaying the legend only fails inline (in an IPython notebook). It also failed for me to display the legend using qt (on Mac).
from ggplot import *
import pandas as pd
%matplotlib inline
The meat data frame in its original form.
print meat.head (2)
date beef veal pork lamb_and_mutton broilers other_chicken \
0 1944-01-01 751 85 1280 89 NaN NaN
1 1944-02-01 713 77 1169 72 NaN NaN
turkey
0 NaN
1 NaN
Long form meat data frame.
meat_lng = pd.melt(meat, id_vars=['date'])
print meat_lng.head (2)
date variable value
0 1944-01-01 beef 751
1 1944-02-01 beef 713
plot = ggplot(aes(x='date', y='value', color='variable'), data=meat_lng) \
+ geom_line() \
+ ggtitle("Meat Production by Decade--Missing Legend")
print plot
.. image :: output_6_0.png
<ggplot: (280905345)>
I have a graph in PNG format. How do I insert it here?
I was hoping that a few lines below would become legend.
plot = ggplot(aes(x='date', y='value', color='variable'), data=meat_lng) \
+ geom_line(size=2.0) \
+ ggtitle("Meat Production by Decade")
# Code that I hoped would fix the missing legend problem.
fig = plot.draw()
ax = fig.axes[0]
offbox = ax.artists[0]
offbox.set_bbox_to_anchor((1, 0.5), ax.transAxes)
fig.show()
::
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-11-9cd7998d1503> in <module>()
4 fig = plot.draw()
5 ax = fig.axes[0]
----> 6 offbox = ax.artists[0]
7 offbox.set_bbox_to_anchor((1, 0.5), ax.transAxes)
8 fig.show()
IndexError: list index out of range
source to share
The example you are linking to was done using ggplot version 0.5.8. Something they changed in later versions removed the legend from the scatterplot. There is an open issue related to this on the ggplot github page, but until it gets resolved, if you want the legend to appear, I would recommend using the older version.
source to share