移动 Matplotlib 1.5.1 中的现有图例 [英] Move existing legend in Matplotlib 1.5.1
问题描述
我尝试了上一个问题的答案,但无济于事Matplotlib 1.5.1.
I tried answers from a previous question to no avail in Matplotlib 1.5.1.
我有一个海洋生物:
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)))
这不起作用:
g.ax_joint.legend(loc = 'lower right')
还有这个:
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.
推荐答案
没有简单的方法(使用像 'lower right'
这样的字符串)来重新定位我知道的现有图例.
There is no easy (using strings like 'lower right'
) way to relocate an existing legend that I am aware of.
要获取现有图例的句柄,您可以使用 legend.legendHandles()
.对于标签,legend.get_texts()
会给你 Text
对象.为了检索实际标签,您最好使用 .get_text()
而不是私有属性 _text
.
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')
我之前建议使用 ax.get_legend_handles_labels()
但这将在轴中搜索,而不是图例,在这种情况下没有用.
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.
这篇关于移动 Matplotlib 1.5.1 中的现有图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!