【问题标题】:How to make custom legend in matplotlib如何在 matplotlib 中制作自定义图例
【发布时间】:2021-07-14 14:37:22
【问题描述】:

我目前用 matplotlib 以这种方式生成我的图例:

if t==25:
    l1,l2 = ax2.plot(x320,vTemp320,'or',x320,vAnaTemp320,'-r')
elif t==50:
    l3,l4 = ax2.plot(x320,vTemp320,'ob',x320,vAnaTemp320,'-b')
else:
    l5,l6 = ax2.plot(x320,vTemp320,'og',x320,vAnaTemp320,'-g')
plt.legend((l1,l2,l3,l4,l5,l6), ('t=25 Simulation', 't=25 Analytical','t=50 Simulation', 't=50 Analytical','t=500 Simulation', 't=500 Analytical'),
   bbox_to_anchor=(-.25, 1), loc=2, borderaxespad=0.,prop={'size':12})

以某种方式起作用,请参阅1。但是我的图例中有重复的信息。

我更愿意将图例分开。这样我就有了对应于时间 t 的不同颜色的线条。一条法线作为我的分析解决方案,一个点表示我的模拟结果。

类似的东西

--(红线)t = 25

--(蓝线)t = 50

--(绿线)t = 500

o 模拟

-- 解析解

现在有人知道我可以如何使用 matplotlib 实现这一目标吗?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以选择要在图例中显示的艺术家和标签,如下所示。您需要为图例中未实际绘制的元素创建自定义艺术家。

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.linspace(0,10,31)
    
    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)
    
    #Plot analytic solution
    ax.plot(x,1*x**2, color='r', label="t = 25")
    ax.plot(x,2*x**2, color='b', label="t = 50")
    ax.plot(x,3*x**2, color='g', label="t = 500")
    
    #Plot simulation
    ax.plot(x,1*x**2, color='r', linestyle='', marker='o')
    ax.plot(x,2*x**2, color='b', linestyle='', marker='o')
    ax.plot(x,3*x**2, color='g', linestyle='', marker='o')
    
    #Get artists and labels for legend and chose which ones to display
    handles, labels = ax.get_legend_handles_labels()
    display = (0,1,2)
    
    #Create custom artists
    simArtist = plt.Line2D((0,1),(0,0), color='k', marker='o', linestyle='')
    anyArtist = plt.Line2D((0,1),(0,0), color='k')
    
    #Create legend from custom artist/label lists
    ax.legend([handle for i,handle in enumerate(handles) if i in display]+[simArtist,anyArtist],
              [label for i,label in enumerate(labels) if i in display]+['Simulation', 'Analytic'])
    
    plt.show()
    

    【讨论】:

    • 这可能是一个英语问题,但您所说的“艺术家”是什么意思?
    • @Mr.Squig。模块artist,类Artist
    • 这不再适用于为图例条目创建多个点。一种解决方案是通过括号 (Line2D((0),(0)...), Line2D((1),(0),... ) 将多个 Line2D 艺术家分组,然后使用 handler_map={tuple: HandlerTuple(ndivide=None)}更多信息在这里:matplotlib.org/stable/gallery/text_labels_and_annotations/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 2014-09-19
    • 2021-12-29
    • 1970-01-01
    相关资源
    最近更新 更多