-1

I tried answers from a previous question to no avail in Matplotlib 1.5.1.

I have a seaborn figure:

import seaborn as sns
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
tips = sns.load_dataset("tips")
g = sns.jointplot("total_bill", "tip",  data = tips[["total_bill", "tip"]].applymap(lambda x : -np.log10(x)))

This does not work:

g.ax_joint.legend(loc = 'lower right')

As well as this:

plt.legend(bbox_to_anchor=(1.05, 1), loc=4, borderaxespad=0.)

/usr/local/lib/python3.4/dist-packages/matplotlib/axes/_axes.py:520: UserWarning: No labelled objects found. Use label='...' kwarg on individual plots.
  warnings.warn("No labelled objects found. "

What is the way to locate an existing legend to lower right in this case?


Not an elegant solution for now is:

ll = g.ax_joint.get_legend().get_texts()[0]._text
g.ax_joint.get_legend().remove()
g.ax_joint.text( -12, -12, ll,  fontsize=14)

However, I believe there should be a better way.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Dima Lituiev
  • 12,544
  • 10
  • 41
  • 58
  • 2
    There are some examples on the MatPlotLib docs page, http://matplotlib.org/users/legend_guide.html – Joseph James Feb 22 '16 at 19:53
  • There are examples, but for example ` loc=4` has no effec in my case if I do not provide handles to artists. And in case of seaborn I was not able to find the handles I need. If you know how to get them, please share. – Dima Lituiev Feb 22 '16 at 21:25

1 Answers1

0

There is no easy (using strings like 'lower right') way to relocate an existing legend that I am aware of.

To get the handles of an existing legend you can use legend.legendHandles(). For the labels, legend.get_texts() will give you the Text objects. In order to retrieve the actual labels you'd better use .get_text() instead of the private attribute _text.

The following will copy the handles and labels of an existing legend to a new one. Other properties of the legend won't be copied.

legend = g.ax_joint.get_legend()
labels = (x.get_text() for x in legend.get_texts())
g.ax_joint.legend(legend.legendHandles, labels, loc='lower right')

I previously suggested using ax.get_legend_handles_labels() but this will search in the axes, not the legend, and is not useful in this case.

Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56
  • 1
    This unfortunately has an effect but not a meaningful one: the `handles` and `labels` returned are empty and the second operation removes legend from figure. This fact that the handles are empty is quite strange as `ll = g.ax_joint.get_legend().get_texts()[0]._text` does return the displayed text. Please see a complete testable example above. – Dima Lituiev Feb 23 '16 at 17:59
  • @DinaLituiev You're right, sir, `ax.get_legend_handles_labels()` won't work in your case. I had issues with the `load_dataset` call and had to test with a made up example that misled me. See my edit. – Stop harming Monica Feb 23 '16 at 19:14