在同一条目上添加带有两条曲线的图例条目,python matplotlib

Adding a legend entry with two curves on same entry, python matplotlib

我想要一个如下图所示的图例:如您所见,图例条目在同一条目上显示了红线和蓝线。

PD:在我的例子中,红线总是同一条曲线,一条水平直线。

我怎样才能做到这一点?我已经尝试使用 this guide 中的示例,但它们不适用于我的案例,因为我没有找到适用于我的案例的“handlebox artist”。

编辑:我尝试应用@Mr.T答案,但在我的例子中,我在matplotlib中将蓝色图绘制为条形图,我得到以下错误 AttributeError: 'BarContainer' object has no attribute '_transform'.

我做的是

blue_bars = axes[i].bar(bins[:-1], Wi, width = binsize, label = label_W)
red_line = axes[i].hlines(0, tstart, tstop, color='red', linewidth = 0.8)
axes[i].legend([red_line, blue_bars], labels = label_W,
            handler_map={blue_bars: HandlerLine2D(numpoints=5)},
            loc='upper right')

请注意,我在同一个轴对象中创建了多个子图,在循环遍历变量 i 的 for 循环中。这没有问题。

基于linked examples,我们可以从头开始构建图例条目,因为您没有告诉我们您是如何绘制图表的:

import matplotlib.pyplot as plt
import matplotlib.lines as mlines
from matplotlib.legend_handler import HandlerLine2D

fig, ax = plt.subplots()
red_hline = mlines.Line2D([], [], color="red")
blue_uptick = mlines.Line2D([], [], color="blue", lw=0, marker=2, markersize=5)
orange_downtick = mlines.Line2D([], [], color="orange", lw=0, marker=3, markersize=5)

ax.legend(handles=[(red_hline, blue_uptick), (red_hline, orange_downtick)], 
          labels=["the ups", "and the downs"], 
          handler_map={blue_uptick: HandlerLine2D(numpoints=5), orange_downtick: HandlerLine2D(numpoints=3)})

plt.show()

示例输出: