matplotlib中的图例设定
matplotlib.pyplot.legend(
handles : 需要设置图例标签的图形元素列表
labels : 相应图形元素的图例标签文字列表
loc = ‘upper right’ : 图例的显示位置,int/string
‘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
也可以按照2-tuple格式直接指定从左下角起的(x, y)坐标值
)
完整参考信息:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html
常见用法:
legend() # 显示图例
legend(labels) # 按默认元素顺序设定标签并显示图例
legend(handles, labels) # 设定指定元素的标签并显示图例
plt.plot([1,2,2,1], label='A line')
plt.plot([1,2,2,1], label='A line')
plt.legend()
plt.plot([1,2,2,1])
plt.legend(['Line Label'])
plt.plot([1,2,2,1])
plt.legend('Line Label') # 错误的设定方式
# 直接指定图例坐标
plt.plot([1,2,2,1])
plt.legend(['Line Label'], loc = (0.5,0.5))
# 此处赋值时需要以逗号结尾,否则返回的是对象列表
l1, = plt.plot([1, 2, 2, 1], label = 'sfsad')
l2, = plt.plot([1, 1.5, 1.5, 1])
plt.legend(handles = [l1, l2],
labels = ['Line Label', 'line2'], loc = 'best')
# 不加逗号则需要准确指定到列表的具体对象
l1 = plt.plot([1,2,2,1])
l2 = plt.plot([1,1.5,1.5,1])
plt.legend(handles = [l1[0], l2[0]],
labels = ['Line Label', 'line2'], loc = 'best')
# 不加逗号则需要准确指定到列表的具体对象
l1 = plt.plot([1,2,2,1])
l2 = plt.plot([1,1.5,1.5,1], label = 'asdasdf')
# 只要求显示某些图形元素的标签
plt.legend(handles = [l1[0]],
labels = ['Line Label'], loc = 'best')
seaborn中的图例设定
图例也可以针对连续变量进行设定,此时可以修改图例的详细程度。
# 显示简化图例
sns.lineplot(x = 's4', y = 'index1', data = ccss, size = 'Qs9', ci = None)
# 完整显示详细图例
sns.lineplot(x = 's4', y = 'index1', data = ccss, size = 'Qs9',
legend = 'full', ci = None)
面板图形中的图例显示位置
# 面板图形中图例显示在外部
sns.lmplot(x = "s3", y="index1", hue = "s2", col = "s0", data = ccss)
# 面板图形中图例显示在内部
sns.lmplot(x = "s3", y="index1", hue = "s2", col = "s0",
data = ccss, legend_out = False)