【问题标题】:Insert image into pie chart slice将图像插入饼图切片
【发布时间】:2017-11-15 14:48:50
【问题描述】:

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

我可以生成图像,甚至可以绘制图像而不是像这里演示的点 Matplotlib: How to plot images instead of points?

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

【问题讨论】:

    标签: python image matplotlib python-imaging-library


    【解决方案1】:

    这肯定是可能的。我们可以从普通的pie chart 开始。然后我们需要将图像放入情节中。这是使用plt.imreadmatplotlib.offsetbox.OffsetImage 完成的。我们需要找到合适的坐标和缩放级别来放置图像,使其与相应的饼形楔形完全重叠。然后饼的楔形路径被用作图像的clip path,这样就只剩下楔形内部的部分了。将未填充楔形的 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()
    

    【讨论】:

    • 谢谢。有用。我需要花一些时间来理解它,但我得到了它的工作。再次感谢,我在这上面花了很长时间,然后我决定问一下。我会试着让它现在完全工作。我没有足够的声望来投票,但值得一票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    相关资源
    最近更新 更多