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

编程入门 行业动态 更新时间:2024-10-25 02:31:19
本文介绍了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文档中有关于该确切主题的部分: matplotlib/users/legend_guide.html#multiple-legends-on-the-same-axes

There's a section in the matplotlib documentation on that exact subject: matplotlib/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个不同的图例

本文发布于:2023-11-06 22:48:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564883.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图上   图例   matplotlib

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!