简体   繁体   English

如何为一个绘图实例创建两个图例对象?

[英]How to create two legend objects for a single plot instance?

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)

条形图

I would like to show both the red and blue colors in the legend object. 我想在图例对象中同时显示红色和蓝色。 I can think of 2 visually appealing ideas. 我可以想到2个吸引人的想法。 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. 我看了matplotlib文档,我很困惑。 How can I go about doing this? 我该怎么做呢?

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. 我猜一个简单的选择是使用matplotlib.legend_handler.HandlerTuple并为图例句柄提供一个红色和蓝色矩形的元组。

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 . 另外,您当然可以按照图例指南的说明使用任何喜欢的自定义处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM