您的位置:宽带测速网 > 编程知识 > Seaborn的legend()函数如何使用

Seaborn的legend()函数如何使用

2025-07-04 09:10来源:互联网 [ ]

在Seaborn中,legend()函数用于控制图表中的图例。可以通过legend()函数的参数来设置图例的位置、是否显示、标题等属性。

下面是一个简单的例子,演示如何使用legend()函数:

import seaborn as snsimport matplotlib.pyplot as plt# 创建一个示例数据集tips = sns.load_dataset("tips")# 绘制一个柱状图sns.barplot(x="day", y="total_bill", data=tips, hue="sex")# 添加图例并设置属性plt.legend(title='Gender', loc='upper right', bbox_to_anchor=(1, 1))# 显示图表plt.show()

在上面的例子中,我们首先创建了一个柱状图,并通过hue参数设置了图例的标签。然后使用plt.legend()函数来添加图例,并通过参数设置了图例的标题为’Gender’,位置为右上角。最后调用plt.show()函数来显示图表。