以最简单的方式将图例添加到Matplotlib中的PyPlot [英] Adding a legend to PyPlot in Matplotlib in the simplest manner possible

查看:52
本文介绍了以最简单的方式将图例添加到Matplotlib中的PyPlot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL; DR-> 如何在不创建任何额外变量的情况下在MatplotlibPyPlot中为折线图创建图例?

TL;DR -> How can one create a legend for a line graph in Matplotlib's PyPlot without creating any extra variables?

请考虑以下图形脚本:

if __name__ == '__main__':
    PyPlot.plot(total_lengths, sort_times_bubble, 'b-',
                total_lengths, sort_times_ins, 'r-',
                total_lengths, sort_times_merge_r, 'g+',
                total_lengths, sort_times_merge_i, 'p-', )
    PyPlot.title("Combined Statistics")
    PyPlot.xlabel("Length of list (number)")
    PyPlot.ylabel("Time taken (seconds)")
    PyPlot.show()

如您所见,这是matplotlibPyPlot的非常基本的用法.理想情况下,会生成如下图所示的图形:

As you can see, this is a very basic use of matplotlib's PyPlot. This ideally generates a graph like the one below:

没什么特别的,我知道.但是,尚不清楚在何处绘制哪些数据(我正在尝试绘制某些排序算法的数据,长度与所用时间的关系,并且我想确保人们知道哪条线是哪条).因此,我需要一个图例,不过,请看下面的以下示例(官方网站上的 ):

Nothing special, I know. However, it is unclear what data is being plotted where (I'm trying to plot the data of some sorting algorithms, length against time taken, and I'd like to make sure people know which line is which). Thus, I need a legend, however, taking a look at the following example below(from the official site):

ax = subplot(1,1,1)
p1, = ax.plot([1,2,3], label="line 1")
p2, = ax.plot([3,2,1], label="line 2")
p3, = ax.plot([2,3,1], label="line 3")

handles, labels = ax.get_legend_handles_labels()

# reverse the order
ax.legend(handles[::-1], labels[::-1])

# or sort them by labels
import operator
hl = sorted(zip(handles, labels),
            key=operator.itemgetter(1))
handles2, labels2 = zip(*hl)

ax.legend(handles2, labels2)

您将看到我需要创建一个额外的变量ax.如何在不创建此额外变量并保持当前脚本简单性的情况下,向图 中添加图例?

You will see that I need to create an extra variable ax. How can I add a legend to my graph without having to create this extra variable and retaining the simplicity of my current script?

推荐答案

向每个 plot() 调用,然后调用 legend(loc='upper left') .

请考虑以下示例(已通过Python 3.8.0测试):

Consider this sample (tested with Python 3.8.0):

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, "-b", label="sine")
plt.plot(x, y2, "-r", label="cosine")
plt.legend(loc="upper left")
plt.ylim(-1.5, 2.0)
plt.show()

从本教程中略作修改: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1 .html

Slightly modified from this tutorial: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html

这篇关于以最简单的方式将图例添加到Matplotlib中的PyPlot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆