matplotlib.legend函数的用法
·
plt.legend()函数的作用是给图像加图例。
图例是集中于地图一角或一侧的地图上各种符号和颜色所代表内容与指标的说明,有助于更好的认识地图。
官方手册对该函数的功能进行了详细的介绍
博主对matplotlib中其他函数也有介绍
下面对其中常用的一些功能做简单汇总:
1、设置图例位置:plt.legend(loc=‘xxx’)
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 |
2、设置图例字体大小
fontsize :int or float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}
图例的字体大小。 如果该值为数字,则大小将是绝对字体大小(以磅为单位)。若是字符串,则相当于当前默认字体大小。仅当未指定prop时才使用此参数。
3、设置图例边框和背景
plt.legend(loc=‘best’,frameon=False) #去掉图例边框
plt.legend(loc=‘best’,edgecolor=‘blue’) #设置图例边框颜色
plt.legend(loc=‘best’,facecolor=‘blue’) #设置图例背景颜色,若无边框,参数无效
4、设置图例标题plt.legend(title=‘xxx’)
plt.legend(title=(‘sinx’, ‘cosx’))则图例如图:
5、设置图例与线条对应关系
可以先在绘制过程中设置label,这样直接在图例中会直接显示线条名词。
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
# 生成数据
x = np.arange(0, 6, 0.1) # 以0.1为单位,生成0到6的数据
y1 = np.sin(x)
y2 = np.cos(x)
# 绘制图形
plt.plot(x, y1, label='sin')
plt.plot(x, y2, linestyle="--", label='cos')
plt.xlabel("x") # x轴的标签
plt.ylabel("y") # y轴的标签
plt.title('sin & cos')
plt.legend()
plt.show()
这样绘制出的图例如图:
阅读全文
AI总结
更多推荐
相关推荐
查看更多
llama_index

LlamaIndex(前身为GPT Index)是一个用于LLM应用程序的数据框架
halo

强大易用的开源建站工具。
freeCodeCamp

freeCodeCamp.org的开源代码库和课程。免费学习编程。
所有评论(0)