Matplotlib--legend图例

官方文档

import seaborn as sns
import matplotlib.pyplot as plt
from numpy import random,linspace
iris = sns.load_dataset('iris')
iris.head()
sepal_lengthsepal_widthpetal_lengthpetal_widthspecies
05.13.51.40.2setosa
14.93.01.40.2setosa
24.73.21.30.2setosa
34.63.11.50.2setosa
45.03.61.40.2setosa
fig = plt.figure()

ax = fig.add_subplot()
plt.scatter(iris['sepal_length'],iris['sepal_width'],label='Legend')

plt.legend()

在这里插入图片描述

legend()不带参数的调用会自动获取图例句柄及其关联的标签。此功能等效于:
fig = plt.figure()

ax = fig.add_subplot()
plt.scatter(iris['sepal_length'],iris['sepal_width'],label='Legend')

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)

在这里插入图片描述

可以通过修改labels来修改legend显示内容
fig = plt.figure()

ax = fig.add_subplot()
sns.set(style='white')
sns.scatterplot('sepal_length', 'sepal_width',
                data=iris,
                palette='muted',
                hue='species')


handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, ["Labels",1,2,3])

在这里插入图片描述

调整legend位置

fig = plt.figure()

ax = fig.add_subplot()
sns.set(style='white')
sns.scatterplot('petal_length', 'petal_width',
                data=iris,
                palette='muted',
                hue='species')


ax.legend(loc='best')

"""
===============   =============
Location String   Location Code
===============   =============
'best'                 0
'upper right'          1
'upper left'           2
'lower left'           3
'lower right'          4
'right'                5
'center left'          6
'center right'         7
'lower center'         8
'upper center'         9
'center'               10
===============   =============
"""

在这里插入图片描述

fig = plt.figure()

ax = fig.add_subplot()
sns.set(style='white')
sns.scatterplot('petal_length', 'petal_width',
                data=iris,
                palette='muted',
                hue='species')


ax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left',
           ncol=2, mode="expand", borderaxespad=0)
"""
bbox_to_anchor:
第一个参数表示图标与左侧的距离,
第二个参数表示图标与下端的距离,
第三个表示legend框线的长度,
第四个表示legend框线的宽度。
仅当mode='expand'时,改变第三四个参数才有效

borderaxespad:
控制legend与ax的距离
"""

在这里插入图片描述

fig = plt.figure()

ax = fig.add_subplot()
sns.set(style='white')
sns.scatterplot('petal_length', 'petal_width',
                data=iris,
                palette='muted',
                hue='species',
                ax=ax)

handles, labels = ax.get_legend_handles_labels()
first_legend = ax.legend(handles=handles[1:-1], loc='upper left')
ax.add_artist(first_legend)

ax.legend(handles=handles[-1:],loc='lower right')

在这里插入图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值