从seaborn p删除图例标题

2024-05-28 23:14:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是想删除一个用seaborn制作的散乱情节的标题。标题由hue参数给定。在这种情况下,标题是“钚”

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)

谢谢!在


Tags: true标题data参数情况pltseabornhue
2条回答

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

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

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

^{pr2}$

代码:

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以了解其他可能的方法

当您使用hue=,或style=等创建一个scatterplot()时,seaborn会自动在图例列表中添加一个条目来充当“节标题”。在

由于您正在重新创建图例以将其放入所需的格式,因此要求matplotlib排除图例列表中的第一个条目以除去该“header”非常简单

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)

相关问题 更多 >

    热门问题