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

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

问题描述

<块引用>

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

请考虑下面的绘图脚本:

如果 __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("组合统计")PyPlot.xlabel("列表长度(数字)")PyPlot.ylabel("所用时间(秒)")PyPlot.show()

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

没什么特别的,我知道.但是,不清楚哪些数据被绘制在何处(我试图绘制一些排序算法的数据,长度与所用时间的关系,我想确保人们知道哪条线是哪条线).因此,我需要一个图例,但是,请看下面的示例(本教程略有修改:http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html

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

Please consider the graphing script below:

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()

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)

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?

解决方案

Add a label= to each of your plot() calls, and then call legend(loc='upper left').

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()

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

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

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