Matplotlib图例指南基本示例 [英] Matplotlib Legend Guide basic examples

查看:112
本文介绍了Matplotlib图例指南基本示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何更好地使用legend(),特别是如何使用代理艺术家.我发现严重缺乏传奇指南.这篇文章有点类似于此文章.

I am trying to understand how to use the legend() better, specifically how to use proxy artists. I find the Legend guide to be severely lacking. This post is somewhat similar to this one.

我正在Windows 7上使用Python 2.7.5,matplotlib版本1.2.1.我写的这段代码实质上是图例指南中示例的组合:

I am using Python 2.7.5 on Windows 7, matplotlib version 1.2.1. I wrote this code which is essentially a combination of the examples in the legend guide:

import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.pyplot as plt

line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')

blue_line = mlines.Line2D([], [], color='blue', marker='*',
                      markersize=15, label='Blue stars')
red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend([red_patch,blue_line])

plt.show()

图例标签的颜色不是在手柄中分配的颜色,也不是补丁和带有星形的线.我尝试过删除和添加行,在行之后添加和删除逗号,等等.它们是否对于使用legend()有更好的引用?还有其他使用代理艺术家的技巧吗?我不明白为什么这些例子给我完全不同的结果...

The legend label colors are not those assigned in the handles, nor are they a patch and a line with stars. I have tried removing and adding the lines, adding and removing the commas after the lines, etc. Are they any better references for using legend()? Any other tips for using proxy artists? I don't understand why the examples give me totally different results...

推荐答案

我仍在使用matplotlib 1.2.1,因此我将告诉您什么对我有效.我发现,如果将线对象传递给legend(),则还必须分别传递标签. [这也与le​​gened()上的matplotlib文档一致.我已经稍微修改了您的示例以执行此操作,并且它似乎可以正常工作:

I'm still using matplotlib 1.2.1 so I'll tell you what works for me. I find that if I pass the line objects to legend(), I also have to pass the labels separately. [This is also consistent with the matplotlib documentation on legened()]. I've modified your example slightly to do this, and it seems to work:

import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.pyplot as plt

line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')

blue_line = mlines.Line2D([], [], color='blue', marker='*',
                  markersize=15, label='Blue stars')
red_patch = mpatches.Patch(color='red', label='The red data')

lines = [blue_line, red_patch]
labels = [line.get_label() for line in lines]
plt.legend(lines, labels)

plt.show()

这篇关于Matplotlib图例指南基本示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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