博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
matplotlib 画图
阅读量:4028 次
发布时间:2019-05-24

本文共 9115 字,大约阅读时间需要 30 分钟。

https://matplotlib.org/users/legend_guide.html

Legend guide

This legend guide is an extension of the documentation available at  - please ensure you are familiar with contents of that documentation before proceeding with this guide.

This guide makes use of some common terms, which are documented here for clarity:

legend entry
A legend is made up of one or more legend entries. An entry is made up of exactly one key and one label.
legend key
The colored/patterned marker to the left of each legend label.
legend label
The text which describes the handle represented by the key.
legend handle
The original object which is used to generate an appropriate entry in the legend.

Controlling the legend entries

Calling  with no arguments automatically fetches the legend handles and their associated labels. This functionality is equivalent to:

handles, labels = ax.get_legend_handles_labels()ax.legend(handles, labels)

The  function returns a list of handles/artists which exist on the Axes which can be used to generate entries for the resulting legend - it is worth noting however that not all artists can be added to a legend, at which point a “proxy” will have to be created (see  for further details).

For full control of what is being added to the legend, it is common to pass the appropriate handles directly to :

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

In some cases, it is not possible to set the label of the handle, so it is possible to pass through the list of labels to :

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

Creating artists specifically for adding to the legend (aka. Proxy artists)

Not all handles can be turned into legend entries automatically, so it is often necessary to create an artist which can. Legend handles don’t have to exists on the Figure or Axes in order to be used.

Suppose we wanted to create a legend which has an entry for some data which is represented by a red color:

import matplotlib.patches as mpatchesimport matplotlib.pyplot as pltred_patch = mpatches.Patch(color='red', label='The red data')plt.legend(handles=[red_patch])plt.show()

(, , )

../_images/legend_guide-1.png

There are many supported legend handles, instead of creating a patch of color we could have created a line with a marker:

import matplotlib.lines as mlinesimport matplotlib.pyplot as pltblue_line = mlines.Line2D([], [], color='blue', marker='*',                          markersize=15, label='Blue stars')plt.legend(handles=[blue_line])plt.show()

(, , )

../_images/legend_guide-2.png

Legend location

The location of the legend can be specified by the keyword argument loc. Please see the documentation at  for more details.

The bbox_to_anchor keyword gives a great degree of control for manual legend placement. For example, if you want your axes legend located at the figure’s top right-hand corner instead of the axes’ corner, simply specify the corner’s location, and the coordinate system of that location:

plt.legend(bbox_to_anchor=(1, 1),           bbox_transform=plt.gcf().transFigure)

More examples of custom legend placement:

import matplotlib.pyplot as pltplt.subplot(211)plt.plot([1,2,3], label="test1")plt.plot([3,2,1], label="test2")# Place a legend above this subplot, expanding itself to# fully use the given bounding box.plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,           ncol=2, mode="expand", borderaxespad=0.)plt.subplot(223)plt.plot([1,2,3], label="test1")plt.plot([3,2,1], label="test2")# Place a legend to the right of this smaller subplot.plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)plt.show()

(, , )

../_images/simple_legend01.png

Multiple legends on the same Axes

Sometimes it is more clear to split legend entries across multiple legends. Whilst the instinctive approach to doing this might be to call the function multiple times, you will find that only one legend ever exists on the Axes. This has been done so that it is possible to call repeatedly to update the legend to the latest handles on the Axes, so to persist old legend instances, we must add them manually to the Axes:

import matplotlib.pyplot as pltline1, = plt.plot([1,2,3], label="Line 1", linestyle='--')line2, = plt.plot([3,2,1], label="Line 2", linewidth=4)# Create a legend for the first line.first_legend = plt.legend(handles=[line1], loc=1)# Add the legend manually to the current Axes.ax = plt.gca().add_artist(first_legend)# Create another legend for the second line.plt.legend(handles=[line2], loc=4)plt.show()

(, , )

../_images/simple_legend02.png

Legend Handlers

In order to create legend entries, handles are given as an argument to an appropriate  subclass. The choice of handler subclass is determined by the following rules:

  1. Update  with the value in the handler_map keyword.
  2. Check if the handle is in the newly created handler_map.
  3. Check if the type of handle is in the newly created handler_map.
  4. Check if any of the types in the handle‘s mro is in the newly created handler_map.

For completeness, this logic is mostly implemented in .

All of this flexibility means that we have the necessary hooks to implement custom handlers for our own type of legend key.

The simplest example of using custom handlers is to instantiate one of the existing  subclasses. For the sake of simplicity, let’s choose  which accepts a numpoints argument (note numpoints is a keyword on the  function for convenience). We can then pass the mapping of instance to Handler as a keyword to legend.

import matplotlib.pyplot as pltfrom matplotlib.legend_handler import HandlerLine2Dline1, = plt.plot([3,2,1], marker='o', label='Line 1')line2, = plt.plot([1,2,3], marker='o', label='Line 2')plt.legend(handler_map={
line1: HandlerLine2D(numpoints=4)})

(, , )

../_images/legend_guide-3.png

As you can see, “Line 1” now has 4 marker points, where “Line 2” has 2 (the default). Try the above code, only change the map’s key from line1 totype(line1). Notice how now both  instances get 4 markers.

Along with handlers for complex plot types such as errorbars, stem plots and histograms, the default handler_map has a special tuple handler () which simply plots the handles on top of one another for each item in the given tuple. The following example demonstrates combining two legend keys on top of one another:

import matplotlib.pyplot as pltfrom numpy.random import randnz = randn(10)red_dot, = plt.plot(z, "ro", markersize=15)# Put a white cross over some of the data.white_cross, = plt.plot(z[:5], "w+", markeredgewidth=3, markersize=15)plt.legend([red_dot, (red_dot, white_cross)], ["Attr A", "Attr A+B"])

(, , )

../_images/legend_guide-4.png

Implementing a custom legend handler

A custom handler can be implemented to turn any handle into a legend key (handles don’t necessarily need to be matplotlib artists). The handler must implement a “legend_artist” method which returns a single artist for the legend to use. Signature details about the “legend_artist” are documented at .

import matplotlib.pyplot as pltimport matplotlib.patches as mpatchesclass AnyObject(object):    passclass AnyObjectHandler(object):    def legend_artist(self, legend, orig_handle, fontsize, handlebox):        x0, y0 = handlebox.xdescent, handlebox.ydescent        width, height = handlebox.width, handlebox.height        patch = mpatches.Rectangle([x0, y0], width, height, facecolor='red',                                   edgecolor='black', hatch='xx', lw=3,                                   transform=handlebox.get_transform())        handlebox.add_artist(patch)        return patchplt.legend([AnyObject()], ['My first handler'],           handler_map={
AnyObject: AnyObjectHandler()})

(, , )

../_images/legend_guide-5.png

Alternatively, had we wanted to globally accept AnyObject instances without needing to manually set the handler_map keyword all the time, we could have registered the new handler with:

from matplotlib.legend import LegendLegend.update_default_handler_map({
AnyObject: AnyObjectHandler()})

Whilst the power here is clear, remember that there are already many handlers implemented and what you want to achieve may already be easily possible with existing classes. For example, to produce elliptical legend keys, rather than rectangular ones:

from matplotlib.legend_handler import HandlerPatchimport matplotlib.pyplot as pltimport matplotlib.patches as mpatchesclass HandlerEllipse(HandlerPatch):    def create_artists(self, legend, orig_handle,                       xdescent, ydescent, width, height, fontsize, trans):        center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent        p = mpatches.Ellipse(xy=center, width=width + xdescent,                             height=height + ydescent)        self.update_prop(p, orig_handle, legend)        p.set_transform(trans)        return [p]c = mpatches.Circle((0.5, 0.5), 0.25, facecolor="green",                    edgecolor="red", linewidth=3)plt.gca().add_patch(c)plt.legend([c], ["An ellipse, not a rectangle"],           handler_map={
mpatches.Circle: HandlerEllipse()})

(, , )

../_images/legend_guide-6.png

Known examples of using legend

Here is a non-exhaustive list of the examples available involving legend being used in various ways:

转载地址:http://ddlbi.baihongyu.com/

你可能感兴趣的文章
Matlab与CUDA C的混合编程配置出现的问题及解决方案
查看>>
2017阿里内推笔试题--算法工程师(运筹优化)
查看>>
python自动化工具之pywinauto(零)
查看>>
python一句话之利用文件对话框获取文件路径
查看>>
PaperDownloader——文献命名6起来
查看>>
PaperDownloader 1.5.1——更加人性化的文献下载命名解决方案
查看>>
如何将PaperDownloader下载的文献存放到任意位置
查看>>
C/C++中关于动态生成一维数组和二维数组的学习
查看>>
系统架构:Web应用架构的新趋势---前端和后端分离的一点想法
查看>>
JVM最简生存指南
查看>>
漂亮的代码,糟糕的行为——解决Java运行时的内存问题
查看>>
Java的对象驻留
查看>>
自己动手写GC
查看>>
Java 8新特性终极指南
查看>>
logback高级特性使用(二) 自定义Pattern模板
查看>>
JVM并发机制探讨—内存模型、内存可见性和指令重排序
查看>>
可扩展、高可用服务网络设计方案
查看>>
如何构建高扩展性网站
查看>>
微服务架构的设计模式
查看>>
持续可用与CAP理论 – 一个系统开发者的观点
查看>>