首页 文章

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

提问于
浏览
139

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

如您所见,这是 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 . 如何在我的图形中添加图例,而无需创建此额外变量并保留当前脚本的简单性 .

5 回答

  • 5

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

    二手 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)

  • 8

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

    plt.gca().legend()
    

    您可以在每个 plt.plot() 调用中使用 label= 关键字,或者在 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

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

    ax = plt.gca()
    

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

  • 7

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

    考虑这个样本:

    import numpy as np
    import pylab 
    x = np.linspace(0, 20, 1000)
    y1 = np.sin(x)
    y2 = np.cos(x)
    
    pylab.plot(x, y1, '-b', label='sine')
    pylab.plot(x, y2, '-r', label='cosine')
    pylab.legend(loc='upper left')
    pylab.ylim(-1.5, 2.0)
    pylab.show()
    

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

  • 2

    为绘图调用中的每个参数添加标签,对应于它所绘制的系列,即 label = "series 1"

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

  • 236

    这是一个帮助你的例子......

    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

相关问题