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

如你所见,这是matplotlib's PyPlot的一个非常基本的用法.理想情况下,这会生成如下所示的图形:

Graph

没什么特别的,我知道.然而,目前还不清楚哪些数据被绘制在哪里(我试图绘制一些排序算法的数据,长度与所用时间的关系,我想确保人们知道哪一行是哪一行).因此,我需要一个传说,但是,看看下面的例子(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.我怎样才能在我的graph without中添加一个图例,既要创建这个额外的变量,又要保持当前脚本的简单性?

推荐答案

plot()个呼叫中的每个呼叫中添加label=,然后呼叫legend(loc='upper left').

考虑这个样本(用Python 3.8.测试):

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

enter image description here

Python相关问答推荐

为什么判断pd.DataFrame的值与判断pd.Series的值存在差异(如果索引中有值)?

aiohTTP与pytest的奇怪行为

Tokenizer Docker:无法为Tokenizer构建轮子,这是安装pyproject.toml项目所需的

如何在Pandas 中存储二进制数?

保留包含pandas pandras中文本的列

Python中的Pool.starmap异常处理

如何从格式为note:{neighbor:weight}的字典中构建networkx图?

Tkinter -控制调色板的位置

当值是一个integer时,在Python中使用JMESPath来验证字典中的值(例如:1)

使用Keras的线性回归参数估计

由于NEP 50,向uint 8添加-256的代码是否会在numpy 2中失败?

_repr_html_实现自定义__getattr_时未显示

将两只Pandas rame乘以指数

如何获取TFIDF Transformer中的值?

如何获得每个组的时间戳差异?

Asyncio:如何从子进程中读取stdout?

Django admin Csrf令牌未设置

Polars asof在下一个可用日期加入

如何在Pyplot表中舍入值

寻找Regex模式返回与我当前函数类似的结果