python - 在 matplotlib 中创建一个具有上下边缘的矩形面片

标签 python matplotlib legend-properties

我在 matplotlib 中有以下情节:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch

x=np.linspace(0,2.,100)
y1=np.power(x,2)*2.+x
y2=np.power(x,2)*2-0.2

plt.plot(x,y1,color="k")
plt.plot(x,y2,color="k")

plt.fill_between(x,y1,y2,facecolor=(0,0,0,0.3),lw=0)

我想添加一个与此类似的图例:

legend_elements = [Patch(facecolor=(0,0,0,0.4), edgecolor='k',
                         label='Filled area')]
plt.gca().legend(handles=legend_elements)

这会产生这个:

Plot with filled area

但是,我想从图例中的补丁中删除横向边缘,以匹配我在图中看到的内容(即,我只有上边缘和下边缘)。

我搜索了如何仅绘制 matplotlib 补丁的某些边缘,但没有找到任何内容。这样的事情可能吗?

最佳答案

您可以make your own legend handler通过扩展内置HandlerPolyCollection用于 fill_ Between:

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

x = np.linspace(0, 2., 100)
y1 = np.power(x, 2) * 2 + x
y2 = np.power(x, 2) * 2 - 0.2

plt.plot(x, y1, color="k")
plt.plot(x, y2, color="k")

plt.fill_between(x, y1, y2, fc=(0, 0, 0, 0.3), lw=0, label="Filled area")

class HandlerFilledBetween(mpl.legend_handler.HandlerPolyCollection):
    def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans):
        p = super().create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)[0]
        x0, y0 = p.get_x(), p.get_y()
        x1 = x0 + p.get_width()
        y1 = y0 + p.get_height()
        line_upper = mpl.lines.Line2D([x0, x1], [y1, y1], color='k')
        line_lower = mpl.lines.Line2D([x0, x1], [y0, y0], color='k')
        return [p, line_upper, line_lower]
    
plt.gca().legend(handler_map={mpl.collections.PolyCollection: HandlerFilledBetween()})

enter image description here

关于python - 在 matplotlib 中创建一个具有上下边缘的矩形面片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69836527/

相关文章:

python - 使交互式 matplotlib 窗口不会在每次更新时弹出到前面(Windows 7)

python - matplotlib.imshow() 实际上返回什么对象?如何使用这个对象?

r - 如何在 ggplotguide_colorsteps 中自定义标签?

matlab - 传奇;键/颜色之前的文本/描述?

python - urllib.request.urlopen 不接受带空格的查询字符串

python - 在python中从字典中设置属性

python - PySpark 一次替换多个列中的值

python - 正则表达式匹配错误

python - 如何使用 pcolormesh 在二维网格中绘制特定正方形的轮廓?

r - 将两个图例添加到 image.plot