matplotlib:同一图上有2个不同的图例 [英] matplotlib: 2 different legends on same graph

查看:827
本文介绍了matplotlib:同一图上有2个不同的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图,其中不同的颜色用于不同的参数,不同的线型用于不同的算法.目的是比较使用相似参数执行的不同算法的结果.这意味着我总共使用4种不同的颜色和3种不同的线型,在同一张图上总共使用了12个图.

I have a plot where different colors are used for different parameters, and where different line styles are used for different algorithms. The goal is to compare the results of the different algorithms performed with similar parameters. It means in total I use 4 different colors, and 3 different line styles, for a total of 12 plots on the same graph.

我实际上是根据颜色构建图例的,将每种颜色与相应的参数相关联.现在,我想在同一张图上显示第二个图例,并说明每种线型的含义.有可能实现吗?怎么样?

I actually build the legend based on colors, associating each color with the corresponding parameter. Now I'd like to display a second legend on the same graph, with the meaning of each line style. It is possible to achieve that? How?

这实际上是我的代码:

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

推荐答案

matplotlib文档中有关于该确切主题的部分:

There's a section in the matplotlib documentation on that exact subject: http://matplotlib.org/users/legend_guide.html#multiple-legends-on-the-same-axes

以下是您的特定示例的代码:

Here's code for your specific example:

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)

这是其输出的示例:

Here's an example of its output:

这篇关于matplotlib:同一图上有2个不同的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆