Python 以最简单的方式向 Matplotlib 中的 PyPlot 添加图例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19125722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:56:26  来源:igfitidea点击:

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

pythonmatplotlibplot

提问by Games Brainiac

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

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

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:

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

Graph

图形

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 withouthaving to create this extra variable and retaining the simplicity of my current script?

你会看到我需要创建一个额外的变量ax。如何在无需创建此额外变量并保留当前脚本的简单性的情况下向我的图形添加图例?

采纳答案by Rob?

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

label=为每个plot()调用添加,然后调用legend(loc='upper left')

Consider this sample (tested with Python 3.8.0):

考虑这个示例(使用 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 hereSlightly modified from this tutorial: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html

在此处输入图片说明从本教程稍微修改:http: //jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html

回答by blaklaybul

Add labels to each argument in your plot call corresponding to the series it is graphing, i.e. label = "series 1"

将标签添加到与它正在绘制的系列相对应的绘图调用中的每个参数,即 label = "series 1"

Then simply add Pyplot.legend()to the bottom of your script and the legend will display these labels.

然后只需添加Pyplot.legend()到脚本的底部,图例就会显示这些标签。

回答by Akash Kandpal

Here's an example to help you out ...

这是一个可以帮助您的示例...

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.set_title('ADR vs Rating (CS:GO)')
ax.scatter(x=data[:,0],y=data[:,1],label='Data')
plt.plot(data[:,0], m*data[:,0] + b,color='red',label='Our Fitting 
Line')
ax.set_xlabel('ADR')
ax.set_ylabel('Rating')
ax.legend(loc='best')
plt.show()

enter image description here

在此处输入图片说明

回答by cameronroytaylor

You can access the Axes instance (ax) with plt.gca(). In this case, you can use

您可以使用 访问 Axes 实例 ( ax) plt.gca()。在这种情况下,您可以使用

plt.gca().legend()

You can do this either by using the label=keyword in each of your plt.plot()calls or by assigning your labels as a tuple or list within legend, as in this working example:

您可以通过label=在每次plt.plot()调用中使用关键字或将标签分配为 中的元组或列表legend来执行此操作,如下面的工作示例所示:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)
plt.plot(x,y0,x,y1)
plt.gca().legend(('y0','y1'))
plt.show()

pltGcaLegend

pltGcaLegend

However, if you need to access the Axes instance more that once, I do recommend saving it to the variable axwith

但是,如果您需要多次访问 Axes 实例,我建议将其保存到变量ax

ax = plt.gca()

and then calling axinstead of plt.gca().

然后调用ax而不是plt.gca().

回答by sajalagrawal

A simple plot for sine and cosine curves with a legend.

带有图例的正弦和余弦曲线的简单图。

Used matplotlib.pyplot

用过的 matplotlib.pyplot

import math
import matplotlib.pyplot as plt
x=[]
for i in range(-314,314):
    x.append(i/100)
ysin=[math.sin(i) for i in x]
ycos=[math.cos(i) for i in x]
plt.plot(x,ysin,label='sin(x)')  #specify label for the corresponding curve
plt.plot(x,ycos,label='cos(x)')
plt.xticks([-3.14,-1.57,0,1.57,3.14],['-$\pi$','-$\pi$/2',0,'$\pi$/2','$\pi$'])
plt.legend()
plt.show()

Sin and Cosine plots (click to view image)

正弦和余弦图(点击查看图片)

回答by Boris Yakubchik

You can add a custom legend documentation

您可以添加自定义图例文档

first = [1, 2, 4, 5, 4]
second = [3, 4, 2, 2, 3]
plt.plot(first,'g--', second, 'r--')
plt.legend(['First List','Second List'], loc='upper left')
plt.show()

enter image description here

在此处输入图片说明

回答by James Turner

    # Dependencies
    import numpy as np
    import matplotlib.pyplot as plt

    #Set Axes
    # Set x axis to numerical value for month
    x_axis_data = np.arange(1,13,1)
    x_axis_data

    # Average weather temp
    points = [39, 42, 51, 62, 72, 82, 86, 84, 77, 65, 55, 44]

    # Plot the line
    plt.plot(x_axis_data, points)
    plt.show()

    # Convert to Celsius C = (F-32) * 0.56
    points_C = [round((x-32) * 0.56,2) for x in points]
    points_C

    # Plot using Celsius
    plt.plot(x_axis_data, points_C)
    plt.show()

    # Plot both on the same chart
    plt.plot(x_axis_data, points)
    plt.plot(x_axis_data, points_C)

    #Line colors
    plt.plot(x_axis_data, points, "-b", label="F")
    plt.plot(x_axis_data, points_C, "-r", label="C")

    #locate legend
    plt.legend(loc="upper left")
    plt.show()