import seaborn as sns
import matplotlib.pyplot as plt
from numpy import random,linspace
iris = sns.load_dataset('iris')
iris.head()
|
sepal_length |
sepal_width |
petal_length |
petal_width |
species |
0 |
5.1 |
3.5 |
1.4 |
0.2 |
setosa |
1 |
4.9 |
3.0 |
1.4 |
0.2 |
setosa |
2 |
4.7 |
3.2 |
1.3 |
0.2 |
setosa |
3 |
4.6 |
3.1 |
1.5 |
0.2 |
setosa |
4 |
5.0 |
3.6 |
1.4 |
0.2 |
setosa |
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')