Matplotlib PatchCollection到图例

2024-10-03 15:23:54 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我正在尝试创建一个代理艺术家(?)使用PatchCollections进行修补,然后跟随http://matplotlib.org/users/legend_guide.html生成自定义处理程序。在

然而,我遇到了一个障碍,试图实现这一传奇。legend的参数接受补丁,但不接受patchcollections。在

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.patches as mpatches
from matplotlib.path import Path
from matplotlib.collections import PatchCollection

fig = plt.figure()
ax = fig.add_subplot(111)

verts1 = [(0.,0.),(0.,1.),(1.,1.),(0.51,0.51),(0.,0.),(0.,0.),]
codes1 = [Path.MOVETO,Path.LINETO,Path.LINETO,Path.LINETO,Path.MOVETO,Path.CLOSEPOLY,]
path1 = Path(verts1,codes1)
patch1 = mpatches.PathPatch(path1,ls='dashed',ec='red',facecolor="none")


verts2 = [(0.49,0.49),(0.,0.),(1.,0.),(1.,1.),(0.5,0.5),(0.,0.),]
codes2 = [Path.MOVETO,Path.LINETO,Path.LINETO,Path.LINETO,Path.MOVETO,Path.CLOSEPOLY,]
path2 = Path(verts2,codes2)
patch2 = mpatches.PathPatch(path2,ls='solid',edgecolor='red', facecolor="none")

patch = PatchCollection([patch1,patch2],match_original=True)

ax.set_xlim(-2,2)
ax.set_ylim(-2,2)

ax.add_collection(patch)

Visual

上面是可视化处理程序的代码。基本上是一个矩形,上面的三角形是虚线,下面的三角形是实心的

使用

^{pr2}$

重新创建错误。有解决办法吗?在


Tags: pathfromimport处理程序matplotlibasfigplt
1条回答
网友
1楼 · 发布于 2024-10-03 15:23:54

从这个section中的例子来看,您似乎需要定义一个对象并用把手箱的大小来表示所有坐标

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.patches as mpatches
from matplotlib.path import Path
from matplotlib.collections import PatchCollection

class AnyObject(object):
    pass

class AnyObjectHandler(object):
    def legend_artist(self, legend, orig_handle, fontsize, handlebox):
        x0, y0 = handlebox.xdescent, handlebox.ydescent
        width, height = handlebox.width, handlebox.height
        hw = 0.5*width; hh = 0.5*height
        verts1 = [(x0,y0),(x0,y0+height),(x0+width,y0+height),((x0+hw)*1.01,(y0+hh)*1.01),(x0,y0),(x0,y0),]
        codes1 = [Path.MOVETO,Path.LINETO,Path.LINETO,Path.LINETO,Path.MOVETO,Path.CLOSEPOLY,]
        path1 = Path(verts1,codes1)
        patch1 = mpatches.PathPatch(path1,ls='dashed',ec='red',facecolor="none")

        verts2 = [((x0+hw)*0.99,(y0+hh)*0.99),(x0,y0),(x0+width,y0),(x0+width,y0+height),(x0+hw,y0+hh),(x0,y0),]
        codes2 = [Path.MOVETO,Path.LINETO,Path.LINETO,Path.LINETO,Path.MOVETO,Path.CLOSEPOLY,]
        path2 = Path(verts2,codes2)
        patch2 = mpatches.PathPatch(path2,ls='solid',edgecolor='red', facecolor="none")

        patch = PatchCollection([patch1,patch2],match_original=True)

        handlebox.add_artist(patch)
        return patch


fig = plt.figure()
ax = fig.add_subplot(111)

ax.set_xlim(-2,2)
ax.set_ylim(-2,2)

plt.legend([AnyObject()], ['hellocello'],
           handler_map={AnyObject: AnyObjectHandler()})

plt.show()

对于PatchCollection,这似乎可以正常工作,至少对我来说,matplotlib版本1.4.3是这样的。结果是

enter image description here

相关问题 更多 >