使用plt.legend

时间:2019-05-07 16:57:14

标签: python seaborn legend

尝试使用plt.legend为我的航海散点图自定义图例,文字看起来不错,但会不断破坏相应的图例标记。

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.scatterplot(x="total_bill", y="tip", hue="day",
 data=tips, s=75,  edgecolor='k')

# title
plt.legend(title='Day of Week', labels=['Thursday', 'Friday', 'Saturday', 'Sunday'])

sns.plt.show()

文本看起来不错,但是每个标签旁边的点在第一个标签之后被弄乱了。第一个图例项很好,它会跳过第二个图例项的标记,而后续的图例项会发生偏移。

Results here.

1 个答案:

答案 0 :(得分:0)

基于答案herehere,您需要访问图例对象并修改文本,这在Seaborn中并不像我想象的那么简单。

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.scatterplot(x="total_bill", y="tip", hue="day",
                    data=tips, s=75,  edgecolor='k')

# Assumes Seaborn 0.9.0
legend = g.legend_

# Set legend title
legend.get_texts()[0].set_text('Day of Week')

labels=['Thursday', 'Friday', 'Saturday', 'Sunday']

# Set legend labels
for i, label in enumerate(labels):
    # i+1 because i=0 is the title, and i starts at 0
    legend.get_texts()[i+1].set_text(label) 

# sns.plt.show() for me gives "AttributeError: module 'seaborn' has no attribute 'plt'"
plt.show()

final image