【Matplotlib】 增加图例
2016-07-05 09:38
579 查看
相关文档:
Legend guide
legend() command
Legend API
get_legend_handles_labels()方法返回 存在于图像中的 handles/artists 列表,这些图像可以用来生成结果图例中的入口。值得注意的是并不是所有的 artists 都可以被添加到图例中。
为了全部控制添加到图例中的内容,通常直接传递适量的 handles 给legend()函数。
某些情况下,不太可能设置 handle 的 label,所以需要传递 labels 的列表给 legend()。
综合例子如下:
图像表现形式如下:
Legend guide
legend() command
Legend API
控制图例入口
无参调用 legend() 会自动获取图例handles以及相关的
labels。其对应于以下代码:
handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels)
get_legend_handles_labels()方法返回 存在于图像中的 handles/artists 列表,这些图像可以用来生成结果图例中的入口。值得注意的是并不是所有的 artists 都可以被添加到图例中。
为了全部控制添加到图例中的内容,通常直接传递适量的 handles 给legend()函数。
line_up, = plt.plot([1,2,3], label='Line 2') line_down, = plt.plot([3,2,1], label='Line 1') plt.legend(handles=[line_up, line_down])
某些情况下,不太可能设置 handle 的 label,所以需要传递 labels 的列表给 legend()。
line_up, = plt.plot([1,2,3], label='Line 2') line_down, = plt.plot([3,2,1], label='Line 1') plt.legend([line_up, line_down], ['Line Up', 'Line Down'])
综合例子如下:
import numpy as np import matplotlib.pyplot as plt plt.figure(figsize=(8,5), dpi=80) plt.subplot(111) X = np.linspace(-np.pi, np.pi, 256,endpoint=True) C = np.cos(X) S = np.sin(X) plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data',0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data',0)) plt.xlim(X.min() * 1.1, X.max() * 1.1) plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) plt.ylim(C.min() * 1.1, C.max() * 1.1) plt.yticks([-1, +1], [r'$-1$', r'$+1$']) plt.legend(loc='upper left') plt.show()
图像表现形式如下:
相关文章推荐
- php 导出数据保存为csv
- 【转载】PHP 开发者该知道的 5 个 Composer 小技巧
- php count你真的会用吗?
- 配置editplus,让本地文件直接上传到ftp对应目录中
- Regular expression to match PHP function names
- LAMP--5.测试 php 解析
- LAMP--4.php 编译安装
- ContentProvider
- ThinkPHP之疑难杂症(二)
- ThinkPHP之疑难杂症(一)
- laravel 控制器里 redirect url地址传两个参数的方法
- php 复习
- 浅谈web应用成长的三个阶段
- PHP编译,执行make报错
- PHP单链表的实现代码
- PHP开发中涉及到emoji表情的几种处理方法
- PHP SPL笔记
- php xampp && mysql
- PHP7新功能及语法变化总结
- PHP图片上传