首页 文章

在python matplotlib中填充多种颜色的多边形

提问于
浏览
2

我使用matplotlib绘制多边形贴片,并且想要用特定颜色填充每个多边形的部分,即制作饼图但是三角形或正方形或六边形 . 有没有办法改变饼图的形状或表示多边形的多种填充颜色?

谢谢!

更新:这是模仿我的意思:

Pie Charts of different shapes

1 回答

  • 4

    您可以创建一个 Matplotlib collection ,然后传递一个数组/颜色列表以用于绘图 .

    请考虑以下示例 . 首先得到一些假形状 .

    import matplotlib.path as mpath
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    import numpy as np
    
    def get_tri(xoff=0, yoff=0, up=1):
    
        verts = [(0.0 + xoff, 0.0 + yoff),
                 (0.5 + xoff, 1.0 * up + yoff),
                 (1.0 + xoff, 0.0 + yoff),
                 (0.0 + xoff, 0.0 + yoff)]
    
        p = mpath.Path(verts, [mpath.Path.MOVETO] + (len(verts)-1)*[mpath.Path.LINETO])
    
        return p
    
    shapes = [get_tri(xoff=x, yoff=y, up=o) for x,y,o in [(0.0, 0,  1),
                                                        (1.0, 0,  1),
                                                        (0.5, 1,  1),
                                                        (0.5, 1, -1)]]
    

    从colormap获取颜色:

    cmap = plt.cm.RdYlBu_r
    colors = cmap(np.linspace(0,1, len(shapes)))
    

    并绘制形状:

    fig, ax = plt.subplots(subplot_kw={'aspect': 1.0})
    
    coll = mpl.collections.PathCollection(shapes, facecolor=colors, linewidth=3)
    
    ax.add_collection(coll)
    ax.autoscale_view()
    

    请注意,因为我正在使用 Paths 作为我的形状,我也使用 PathCollection . 如果您使用 Polygons (或其他内容),您还应该使用适当类型的集合,例如 PolyCollection .

    因此,绘制不同颜色非常容易,棘手的部分可能是获取路径/多边形 . 如果您已经拥有它们,则可以将它们放在列表中以创建集合 .

    enter image description here

相关问题