legend()函数

legend显示图例

1 legend基础

函数原型legend(*args, **kwargs)

当len(args) == 2

args是[artist]和[label]的集合

当len(args) == 0

args会自动调用get_legend_handles_labels()生成

等价于

handles, labels = ax.get_legend_handles_labels()

ax.legend(handles, labels)

ax.get_legend_handles_labels()的作用在于返回ax.lines, ax.patch所有对象以及ax.collection中的LineCollectionorRegularPolyCollection对象

注意:这里只提供有限支持,并不是所有的artist都可以被用作图例,比如errorbar支持不完善

1.1调整顺序

ax=subplot(1,1,1)

p1,=ax.plot([1,2,3], label="line1")

p2,=ax.plot([3,2,1], label="line2")

p3,=ax.plot([2,3,1], label="line3")

handles, labels=ax.get_legend_handles_labels()

# reverse the order

ax.legend(handles[::-1], labels[::-1])

# or sort them by labels

importoperatorhl=sorted(zip(handles,labels), key=operator.itemgetter(1))

handles2, labels2=zip(*hl)

ax.legend(handles2, labels2)

1.2使用代理artist

当需要使用legend不支持的artist时,可以使用另一个被legend支持的artist作为代理

比如以下示例中使用不在axe上的一个artist

p=Rectangle((0,0), 1, 1,fc="r")

legend([p], ["RedRectangle"])

2多列图例

ax1=plt.subplot(3,1,1)

ax1.plot([1], label="multinline")

ax1.plot([1], label="$2^{2^2}$")

ax1.plot([1], label=r"$frac{1}{2}pi$")

ax1.legend(loc=1, ncol=3, shadow=True)

ax2=plt.subplot(3,1,2)

myplot(ax2)

ax2.legend(loc="center left", bbox_to_anchor=[0.5,0.5],

ncol=2, shadow=True, title="Legend")

ax2.get_legend().get_title().set_color("red")

3图例位置

ax.legend(…., loc=3)具体对应位置如下图

绘制在图上是这样的,(具体没有分清5和7的区别)

4多个图例

如果不采取措施,连续调用两个legend会使得后面的legend覆盖前面的

frommatplotlib.pyplotimport*p1,=plot([1,2,3], label="test1")

p2,=plot([3,2,1], label="test2")

l1=legend([p1], ["Label1"],loc=1)l2=legend([p2], ["Label2"],loc=4)# this removes l1 from the axes.

gca().add_artist(l1)# add l1 as a separate artist to the axes

5. API

class matplotlib.legend.Legend(parent,handles, labels,**args)

三个最重要的必要参数

parent --- legend的父artist, 包含legend的对象

比如用ax.legend()调用之后

>>> print ax.get_legend().parent

Axes(0.125,0.1;0.775x0.8)

handles ---图例上面画出的各个artist(lines, patches)

labels --- artist对应的标签

其他参数

Keyword

Description

loc

a location code

prop

the font property (matplotlib.font_manager.FontProperties对象)

eg

song_font = matplotlib.font_manager.FontProperties(fname='simsun.ttc', size=8)

fontsize

the font size (和prop互斥,不可同时使用)

markerscale

the relative size of legend markers vs. original

numpoints

the number of points in the legend for line

scatterpoints

the number of points in the legend for scatter plot

scatteryoffsets

a list of yoffsets for scatter symbols in legend

frameon

if True, draw a frame around the legend. If None, use rc

fancybox

if True, draw a frame with a round fancybox. If None, use rc

shadow

if True, draw a shadow behind legend

ncol

number of columns

borderpad

the fractional whitespace inside the legend border

labelspacing

the vertical space between the legend entries

handlelength

the length of the legend handles

handleheight

the length of the legend handles

handletextpad

the pad between the legend handle and text

borderaxespad

the pad between the axes and legend border

columnspacing

the spacing between columns

title

the legend title

bbox_to_anchor

the bbox that the legend will be anchored.

bbox_transform

the transform for the bbox. transAxes if None.

主要函数

get_frame() ---返回legend所在的方形对象

get_lines()

get_patches()

get_texts()

get_title() ---上面几个比较简单,不解释了

set_bbox_to_anchor(bbox, transform=None)

(…本函数待续…之后写axes的时候会加入,目前我没有看懂他的这个长宽和figure以及axes的关系)

6.样例

leg=ax.legend(('Model length','Data length','Total message length'),

'upper center', shadow=True)

# the matplotlib.patches.Rectangle instance surrounding the legend即外框

frame=leg.get_frame()

frame.set_facecolor('0.80')# set the frame face color to light gray

# matplotlib.text.Text instanceslegend中文本

fortinleg.get_texts():

t.set_fontsize('small')# the legend text fontsize

# matplotlib.lines.Line2D instanceslegend中所表示的artist

forlinleg.get_lines():

l.set_linewidth(1.5)# the legend line width

fig=plt.figure()

ax1=fig.add_axes([0.1,0.1,0.4,0.7])

ax2=fig.add_axes([0.55,0.1,0.4,0.7])

x=np.arange(0.0,2.0,0.02)

y1=np.sin(2*np.pi*x)

y2=np.exp(-x)

l1, l2=ax1.plot(x, y1,'rs-', x, y2,'go')

y3=np.sin(4*np.pi*x)

y4=np.exp(-2*x)

l3, l4=ax2.plot(x, y3,'yd-', x, y3,'k^')

fig.legend((l1, l2), ('Line 1','Line 2'),'upper left')

fig.legend((l3, l4), ('Line 3','Line 4'),'upper right')


原文参考:http://blog.sina.com.cn/s/blog_b09d460201019c10.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容