将图像插入饼图切片

Insert image into pie chart slice

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

我可以生成图像甚至绘制图像而不是点,如此处所示 Matplotlib: How to plot images instead of points?

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

当然可以。我们可以从图像的正常 pie chart. Then we would need to get the images into the plot. This is done using plt.imread and by using a matplotlib.offsetbox.OffsetImage. We would need to find good coordinates and zoom levels to place the image, such that it overlapps completely with respective pie wedge. Then the Path of the pie's wedge is used as a 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()