如何为一个绘图实例创建两个图例对象? [英] How to create two legend objects for a single plot instance?

查看:128
本文介绍了如何为一个绘图实例创建两个图例对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下示例代码生成条形图.

I use the following example code to generate a bar plot.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 5, 5)
y = np.exp(x)
w = x[1] - x[0]

colors = ['blue' if idx % 2 == 0 else 'red' for idx in range(len(x))]

fig, ax = plt.subplots()
ax.bar(x, y, width=w, color=colors, label='sample plot')
ax.legend()
plt.show()
plt.close(fig)

我想在图例对象中同时显示红色和蓝色.我可以想到2个吸引人的想法.第一个想法是创建两个围绕图例标签垂直居中的矩形对象(一个红色,另一个蓝色).第二个想法是在图例对象(蓝色)上覆盖矩形(红色)的一半.但是我不知道如何实现这两个目标.我看了matplotlib文档,我很困惑.我该怎么做呢?

I would like to show both the red and blue colors in the legend object. I can think of 2 visually appealing ideas. The first idea is to create two rectangle objects (one red, the other blue) that are vertically centered about the legend label. The second idea is to overlay half of a rectangle (in red) over the legend object (in blue). But I do not know how to accomplish either of these. I have looked at the matplotlib docs, I'm just confused. How can I go about doing this?

推荐答案

我想一个简单的选择是使用matplotlib.legend_handler.HandlerTuple并向图例句柄提供一个红色和蓝色矩形的元组.

I guess an easy option is to use a matplotlib.legend_handler.HandlerTuple and supply a tuple of a red and blue rectangle to the legend handles.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.legend_handler

x = np.linspace(0, 5, 5)
y = np.exp(x)
w = x[1] - x[0]

colors = ['blue' if idx % 2 == 0 else 'red' for idx in range(len(x))]

fig, ax = plt.subplots()
bars = ax.bar(x, y, width=w, color=colors, label='sample plot')

ax.legend(handles = [tuple(bars[:2])], labels=['sample plot'], loc='upper left', 
          handler_map = {tuple: matplotlib.legend_handler.HandlerTuple(None)})

plt.show()

否则,您当然可以使用任何喜欢的自定义处理程序,如图例指南.

Else, you can of course use any custom handler you like as described in the legend guide.

这篇关于如何为一个绘图实例创建两个图例对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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