Matplotlib 添加图例 | 您所在的位置:网站首页 › 怎么添加图例 › Matplotlib 添加图例 |
Matplotlib 添加图例,任何图表都应该有的元素是图例,pyplot专门提供了legend()函数用于添加图例,通过设置参数可以改变图例位置,也支持多图例的显示。 极客教程前面有介绍如何添加网格,本文在此基础上添加图例。 添加图例这里使用legend()函数将图例和字符串类型的图例说明添加到图表中,如下所示,我们把输入的四个数据点统称为”First series”。 import matplotlib.pyplot as plt plt.axis([0,5, 0, 20]) plt.title("geek-docs.com", fontsize=20, fontname="Times New Roman") plt.xlabel('Counting', color = 'gray') plt.ylabel('Square values', color = 'gray') plt.text(1, 1.5, 'First') plt.text(2, 4.5, 'Second') plt.text(3, 9.5, 'Third') plt.text(4, 16.5, 'Fourth') plt.text(1.1, 12, r'$y=x^2', fontsize=20, bbox={'facecolor':'yellow', 'alpha' : 0.2}) plt.grid(True) plt.plot([1,2,3,4], [1,4,9,16], 'ro') plt.legend(['First series']) plt.show()输出结果如下:
如上所示,图例默认添加到图形的右上角。如果要修改图例的位置,还是需要添加几个关键字参数。例如,图例的位置由loc关键字控制,其取值范围为0-10。每个数字代表图表中的一处位置,默认为1,就是右上角位置。 字符串 位置编号 位置表述 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 正中间如下所示,改变图例的显示位置。 import matplotlib.pyplot as plt plt.axis([0,5, 0, 20]) plt.title("geek-docs.com", fontsize=20, fontname="Times New Roman") plt.xlabel('Counting', color = 'gray') plt.ylabel('Square values', color = 'gray') plt.text(1, 1.5, 'First') plt.text(2, 4.5, 'Second') plt.text(3, 9.5, 'Third') plt.text(4, 16.5, 'Fourth') plt.text(1.1, 12, r'$y=x^2', fontsize=20, bbox={'facecolor':'yellow', 'alpha' : 0.2}) plt.grid(True) plt.plot([1,2,3,4], [1,4,9,16], 'ro') plt.legend(['First series'], loc=6) plt.show()输出结果如下:
通常,图例通过标签、颜色或符号向读者表明是哪个序列,应该与其他序列区别开来。前面的例子中,我们只使用了由一个plot()函数绘制的单个序列。现在我们来看看更常见的情况,在一幅图中同时显示了多个序列。图表中每个序列用一种特定的颜色和符号来表示。从代码实现的角度来看,每个序列都要调用一次plot()函数,调用顺序跟传给legend()函数作为参数的文本标签顺序应保持一致。 import matplotlib.pyplot as plt plt.axis([0,5, 0, 20]) plt.title("geek-docs.com", fontsize=20, fontname="Times New Roman") plt.xlabel('Counting', color = 'gray') plt.ylabel('Square values', color = 'gray') plt.text(1, 1.5, 'First') plt.text(2, 4.5, 'Second') plt.text(3, 9.5, 'Third') plt.text(4, 16.5, 'Fourth') plt.text(1.1, 12, r'$y=x^2', fontsize=20, bbox={'facecolor':'yellow', 'alpha' : 0.2}) plt.grid(True) plt.plot([1,2,3,4], [1,4,9,16], 'ro') plt.plot([1,2,3,4], [0.8,3.5,8,15],'g^') plt.plot([1,2,3,4], [0.5,2.5,4,12],'b*') plt.legend(['First series', 'Second Series', 'Third series'], loc=2) plt.show()输出结果如下:
输出结果如下:
极客教程相关文章推荐: Matplotlib 添加网格 Matplotlib 添加文本 Matplotlib Numpy Matplotlib Pyplot |
CopyRight 2018-2019 实验室设备网 版权所有 |