结合两个Pyplot补丁进行图例 [英] Combine two Pyplot patches for legend

查看:74
本文介绍了结合两个Pyplot补丁进行图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制带有置信带的数据.我使用每个数据流的两个图进行此操作:plotfill_between.我希望图例看起来与图相似,其中每个条目都有一个框(置信区域的颜色),其中有一条穿过中心的深色实线.到目前为止,我已经能够使用补丁来创建矩形图例键,但是我不知道如何获得中心线.我尝试使用阴影线,但是无法控制位置,厚度或颜色.

I am trying to plot some data with confidence bands. I am doing this with two plots for each data stream: plot, and fill_between. I would like the legend to look similar to the plots, where each entry has a box (the color of the confidence region) with a darker, solid line passing through the center. So far I have been able to use patches to create the rectangle legend key, but I don't know how to achieve the centerline. I tried using hatch, but there is no control over the placement, thickness, or color.

我最初的想法是尝试合并两个补丁(Patch和2DLine);但是,它还没有起作用.有没有更好的方法?我的MWE和当前数据如下所示.

My original idea was to try and combine two patches (Patch and 2DLine); however, it hasn't worked yet. Is there a better approach? My MWE and current figure are shown below.

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,1,11)
y = np.linspace(0,1,11)

plt.plot(x, y, c='r')
plt.fill_between(x, y-0.2, y+0.2, color='r', alpha=0.5)
p = mpatches.Patch(color='r', alpha=0.5, linewidth=0)

plt.legend((p,), ('Entry',))

推荐答案

该解决方案是从CrazyArm的注释中借用的,位于以下位置:

The solution is borrowed from the comment by CrazyArm, found here: Matplotlib, legend with multiple different markers with one label. Apparently you can make a list of handles and assign only one label and it magically combines the two handles/artists.

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,1,11)
y = np.linspace(0,1,11)

p1, = plt.plot(x, y, c='r')  # notice the comma!
plt.fill_between(x, y-0.2, y+0.2, color='r', alpha=0.5)
p2 = mpatches.Patch(color='r', alpha=0.5, linewidth=0)

plt.legend(((p1,p2),), ('Entry',))

这篇关于结合两个Pyplot补丁进行图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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