从seaborn情节中删除图例标题[重复项]

问题描述 投票:0回答:2

此问题已经在这里有了答案:

我只是想删除用seaborn制作的散点图的标题。标题由hue参数给出。在这种情况下,标题为“ Pluton”

“”

x = sns.scatterplot(x="Al total", y="Fe/Fe+Mg", data=df, hue="Pluton", alpha=1)
sns.set_style("ticks")

plt.legend(ncol=3, loc='upper center', 
           bbox_to_anchor=[0.5, 1.25], 
           columnspacing=1.3, labelspacing=0.0,
           handletextpad=0.0, handlelength=1.5,
           fancybox=True, shadow=True)


plt.ylim(0.2 ,1.1)

谢谢!

python matplotlib seaborn
2个回答
0
投票

[当创建带有scatterplot()hue=等的style=时,seaborn会自动在图例列表中添加一个条目以充当“节标题”。

由于您正在重新创建图例以将其设置为所需格式,因此要求matplotlib排除图例列表中的第一个条目以摆脱该“标题”是很简单的。

tips = sns.load_dataset('tips')
ax = sns.scatterplot(x="total_bill", y="tip", hue="day",
                     data=tips)
h,l = ax.get_legend_handles_labels()
plt.legend(h[1:],l[1:],ncol=3, loc='upper center', 
           bbox_to_anchor=[0.5, 1.25], 
           columnspacing=1.3, labelspacing=0.0,
           handletextpad=0.0, handlelength=1.5,
           fancybox=True, shadow=True)

0
投票

您可以找到图柄和标签-并从它们两个中删除图例标题。它们将是列表,其中包含图例作为第一项。例如,您的示例的labels如下所示:

labels = ['Pluton', 'Desemborque', 'Desemb. (hidrot. I)' ... and all others]

[handles将包含类似的项目,但它们表示为matplotlib object

handles = [<matplotlib.lines.Line2D object at 0x7f114408bf98>, ... and many others]

代码:

import matplotlib.pyplot as plt
import seaborn as sns
# Set style for seaborn
sns.set_style("ticks")

x = sns.scatterplot(x="Al total", y="Fe/Fe+Mg", data=df, hue="Pluton", alpha=1)
# Found handles and labels for legend
ax = x.axes[0][0]
handles, labels = ax.get_legend_handles_labels()
# When set legend in matplotlib use our modified handles and labels
plt.legend(ncol=3, loc='upper center', 
           bbox_to_anchor=[0.5, 1.25], 
           columnspacing=1.3, labelspacing=0.0,
           handletextpad=0.0, handlelength=1.5,
           fancybox=True, shadow=True,
           handles=handles[1:], labels=labels[1:],
          )
# Plot
plt.ylim(0.2, 1.1)
plt.show()

可能建议也阅读this以了解其他可能的方法

© www.soinside.com 2019 - 2024. All rights reserved.