将图像插入饼图切片

发布于 2021-01-29 15:00:44

我正在使用python
3.5.2,我想制作一个嵌入了png图像的饼图。我有一些我想插入切片的散装产品的图片。例如,一片草莓,另一片覆盆子。就像http://www.python-
course.eu/images/pie_chart_with_raspberries.png
显示的图片一样。

我可以生成图像,甚至可以绘制图像而不是点,如此处所示Matplotlib:如何绘制图像而不是点?

但是,对于我的建议,我找不到任何方法。我想可以用油漆手动完成,但是我试图避免这种情况。

关注者
0
被浏览
88
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    在此处输入图片说明

    那肯定是可能的。我们可以从正常的饼图开始。然后,我们需要将图像放入图中。这是通过plt.imread和通过使用来完成的matplotlib.offsetbox.OffsetImage。我们将需要找到合适的坐标和缩放级别来放置图像,以使其与各自的饼图完全重叠。然后,将饼的楔形路径用作图像的剪切路径,以便仅保留楔形内的部分。将未填充的楔形的zorder设置为较高的数字可确保将边框放置在图像的顶部。这样看起来像是楔子充满了图像。

    import matplotlib.pyplot as plt
    from matplotlib.patches import PathPatch
    from matplotlib.offsetbox import OffsetImage, AnnotationBbox
    
    total = [5,7,4]
    labels = ["Raspberries", "Blueberries", "Blackberries"]
    plt.title('Berries')
    plt.gca().axis("equal")
    wedges, texts = plt.pie(total, startangle=90, labels=labels,
                            wedgeprops = { 'linewidth': 2, "edgecolor" :"k","fill":False,  })
    
    
    def img_to_pie( fn, wedge, xy, zoom=1, ax = None):
        if ax==None: ax=plt.gca()
        im = plt.imread(fn, format='png')
        path = wedge.get_path()
        patch = PathPatch(path, facecolor='none')
        ax.add_patch(patch)
        imagebox = OffsetImage(im, zoom=zoom, clip_path=patch, zorder=-10)
        ab = AnnotationBbox(imagebox, xy, xycoords='data', pad=0, frameon=False)
        ax.add_artist(ab)
    
    positions = [(-1,0.3),(0,-0.5),(0.5,0.5)]
    zooms = [0.4,0.4,0.4]
    
    for i in range(3):
        fn = "data/{}.png".format(labels[i].lower())
        img_to_pie(fn, wedges[i], xy=positions[i], zoom=zooms[i] )
        wedges[i].set_zorder(10)
    
    plt.show()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看