Move existing legend in Matplotlib 1.5.1

2019-06-14 19:34发布

问题:

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.

回答1:

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.