首页 文章

matplotlib:同一图表上的2个不同的图例

提问于
浏览
48

我有一个图表,其中不同的颜色用于不同的参数,并且不同的线条样式用于不同的算法 . 目标是比较使用类似参数执行的不同算法的结果 . 这意味着我总共使用了4种不同的颜色和3种不同的线条样式,在同一个图形上总共有12个图形 .

我实际上是根据颜色构建图例,将每种颜色与相应的参数相关联 . 现在我想在同一个图表上显示第二个图例,其中包含每个线条样式的含义 . 有可能实现这一目标吗?怎么样?

这是我的代码实际上是这样的:

colors = ['b', 'r', 'g', 'c']
cc = cycle(c)
for p in parameters:

    d1 = algo1(p)
    d2 = algo2(p)
    d3 = algo3(p)

    pyplot.hold(True)
    c = next(cc)
    pyplot.plot(d1, '-', color=c, label="d1")
    pyplot.plot(d1, '--', color=c)
    pyplot.plot(d2, '.-', color=c)

pyplot.legend()

2 回答

  • 64

    matplotlib文档中有关于该主题的部分:http://matplotlib.org/users/legend_guide.html#multiple-legends-on-the-same-axes

    以下是您的具体示例的代码:

    import itertools
    from matplotlib import pyplot
    
    colors = ['b', 'r', 'g', 'c']
    cc = itertools.cycle(colors)
    plot_lines = []
    for p in parameters:
    
        d1 = algo1(p)
        d2 = algo2(p)
        d3 = algo3(p)
    
        pyplot.hold(True)
        c = next(cc)
        l1, = pyplot.plot(d1, '-', color=c)
        l2, = pyplot.plot(d2, '--', color=c)
        l3, = pyplot.plot(d3, '.-', color=c)
    
        plot_lines.append([l1, l2, l3])
    
    legend1 = pyplot.legend(plot_lines[0], ["algo1", "algo2", "algo3"], loc=1)
    pyplot.legend([l[0] for l in plot_lines], parameters, loc=4)
    pyplot.gca().add_artist(legend1)
    

    以下是其输出示例:
    Plot with 2 legends, per-param and per-algo

  • 6

    这里也是一种更“亲身实践”的方式(即与任何图形轴明确地交互):

    import itertools
    from matplotlib import pyplot
    
    fig, axes = plt.subplot(1,1)
    
    colors = ['b', 'r', 'g', 'c']
    cc = itertools.cycle(colors)
    plot_lines = []
    for p in parameters:
    
        d1 = algo1(p)
        d2 = algo2(p)
        d3 = algo3(p)
    
        c = next(cc)
        axes.plot(d1, '-', color=c)
        axes.plot(d2, '--', color=c)
        axes.plot(d3, '.-', color=c)
    
    # In total 3x3 lines have been plotted
    lines = axes.get_lines()
    legend1 = pyplot.legend([lines[i] for i in [0,1,2]], ["algo1", "algo2", "algo3"], loc=1)
    legend2 = pyplot.legend([lines[i] for i in [0,3,6]], parameters, loc=4)
    axes.add_artist(legend1)
    axes.add_artist(legend2)
    

    我喜欢这种写作方式,因为它允许以不太模糊的方式使用不同的轴 . 您可以先创建一组图例,然后使用方法“add_artist”将它们添加到所需的轴 . 另外,我从matplotlib开始,对我来说,至少在说明objets时更容易理解脚本 .

    注意:小心,你的传说可能在显示/保存时被切断 . 要解决此问题,请使用方法axes.set_position([left,bottom,width,length])相对于图形大小缩小子图,并显示图例 .

相关问题