gpt4 book ai didi

python - 以最简单的方式在 Matplotlib 中的 PyPlot 中添加图例

转载 作者:IT老高 更新时间:2023-10-28 12:19:15 26 4
gpt4 key购买 nike

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 的一个非常基本的用法。理想情况下,这会生成如下图:

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。如何在我的图表中添加图例而不必创建这个额外的变量并保持我当前脚本的简单性?

最佳答案

为您的每个 plot() 添加一个 label=电话,然后调用legend(loc='upper left') .

考虑这个示例(使用 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()

enter image description here对本教程稍作修改:http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html

关于python - 以最简单的方式在 Matplotlib 中的 PyPlot 中添加图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19125722/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com