问题:以最简单的方式将图例添加到Matplotlib中的PyPlot
TL; DR->如何在不创建任何额外变量
Matplotlib的PyPlot情况下为的线形图创建图例?
请考虑以下图形脚本:
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的PyPlot。理想情况下,生成如下图所示的图:

我知道没什么特别的。但是,尚不清楚在何处绘制哪些数据(我正在尝试绘制某些排序算法的数据,长度与所用时间的关系,并且我想确保人们知道哪条线是哪条)。因此,我需要一个图例,不过,请看下面的示例(来自官方网站):
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。如何在图例中添加图例而不必创建此额外变量并保持当前脚本的简单性?
回答 0
label=在每个plot()呼叫中添加一个,然后呼叫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() 从本教程中略作修改:http : //jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html
从本教程中略作修改:http : //jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html
回答 1
您可以使用访问Axes实例(ax)plt.gca()。在这种情况下,您可以使用
plt.gca().legend()您可以通过label=在每个plt.plot()调用中使用关键字或通过将标签分配为元组或list中的列表来做到这一点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()但是,如果您需要多次访问Axes实例,建议您使用以下命令将其保存到变量ax中:
ax = plt.gca()然后呼叫ax而不是plt.gca()。
回答 2
这是一个帮助您的示例…
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()回答 3
一个带有图例的正弦和余弦曲线的简单图解。
用过的 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()
回答 4
将标签添加到绘图调用中与绘图系列相对应的每个参数,即 label = "series 1"
然后只需将其添加Pyplot.legend()到脚本的底部,图例将显示这些标签。
回答 5
您可以添加自定义图例文档
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()回答 6
    # 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()
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。




