data frame plotting with a legend with custom labels

3,002 views
Skip to first unread message

Fabrizio Pollastri

unread,
Aug 23, 2012, 7:55:45 AM8/23/12
to pystat...@googlegroups.com
Hello,

I have found here http://stackoverflow.com/questions/11348183/pandas-bar-plot-with-specific-colors-and-legend-location how to plot a legend with custom labels.

The code seems not working when one plot has secondary_y set to True: all labels corresponding to primary y are plotted, the label corresponding to secondary y isn't plotted.

Thanks in advance for any help,
Fabrizio

Wouter Overmeire

unread,
Aug 23, 2012, 9:11:25 AM8/23/12
to pystat...@googlegroups.com


2012/8/23 Fabrizio Pollastri <are...@gmail.com>


I get labels for both axes (0.8.2.dev). If you want to change the labels (so not using the column labels), that is off to matplotlib.


In [53]: x = np.arange(-pi, pi, .01)

In [54]: df1 = pandas.DataFrame({'sin': sin(x), 'cos': cos(x)}, index=x)

In [55]: df2 = pandas.DataFrame({'x^2': x * x, 'x^3': x * x * x}, index=x)

In [56]: ax = df1.plot()

In [57]: ax.hold(True)

In [58]: df2.plot(ax=ax, secondary_y=True, style='--')
Out[58]: <matplotlib.axes.Axes at 0xc0f554c>


See screenshot for the plot.

Fabrizio Pollastri

unread,
Aug 23, 2012, 1:53:20 PM8/23/12
to pystat...@googlegroups.com

For anyone interested, I have found the following solution for setting arbitrary labels into legend.

 x = arange(-pi, pi, .01)
df1 = DataFrame({'sin': sin(x), 'cos': cos(x)}, index=x)
df2 = DataFrame({'x^2': x * x, 'x^3': x * x * x}, index=x)

ax1 = df1.plot(legend=False)
ax2 = df2.plot(ax=ax1, secondary_y=True, style='--',legend=False)

# get current labels info from both primary and secondary axes
patches1, labels1 = ax1.get_legend_handles_labels()
patches2, labels2 = ax2.get_legend_handles_labels()

# set my arbitrary labels
my_labels = ['my sin','my cos','my x^2','my x^3']
ax1.legend(patches1 + patches2,my_labels)

Fabrizio

Manuel Carrasco

unread,
Apr 8, 2015, 6:35:10 PM4/8/15
to pystat...@googlegroups.com
Thanks, still useful trick!
Reply all
Reply to author
Forward
0 new messages