在matplotlib中将多个饼图分开

Ale*_*x S 8 python matplotlib pie-chart

我非常喜欢matplotlib饼图上的"爆炸"选项.我希望能够"分组爆炸".我正在绘制许多属于3或4类的小切片.作为小组,我想把所有的小片一起爆炸.

我认为这并不完全清楚,所以我呼吁我非常缺乏绘制基本形状的能力,并使这张照片显示我正在尝试做的事情:

分组,爆炸的馅饼

请注意组之间的小阴影.

这可能吗?

非常感谢,Alex

Jak*_*kob 9

我不知道有任何指定分组爆炸馅饼的直接方法,但是使用补丁来重新绘制像这样的组的馅饼非常简单

# original part (left)
import numpy as np
import matplotlib.pyplot as plt
f,ax = plt.subplots(1,2) 
ax[0].set_aspect('equal')
data=np.abs(np.random.randn(7))
wedges, texts = ax[0].pie(data)

# redraw plot using patches (right)
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
ax[1].set_aspect('equal')
ax[1].axis('off')

groups=[[0,1,2],[3,4],[5,6]]
radfraction = 0.1
patches = []
for i in groups:
  ang = np.deg2rad((wedges[i[-1]].theta2 + wedges[i[0]].theta1)/2,)
  for j in i:
    we = wedges[j]
    center = (radfraction*we.r*np.cos(ang), radfraction*we.r*np.sin(ang))
    patches.append(mpatches.Wedge(center, we.r, we.theta1, we.theta2))

colors = np.linspace(0, 1, len(patches))
collection = PatchCollection(patches, cmap=plt.cm.hsv)
collection.set_array(np.array(colors))
ax[1].add_collection(collection)
ax[1].autoscale(True)
Run Code Online (Sandbox Code Playgroud)

这可能会导致像这样的情节
在此输入图像描述

当然,您可以根据数据计算所需的θ角度,而不是使用预先计算的角度.


Joh*_*anC 8

这是 @Jakob 答案的更独立版本,就地更改楔形,并移动标签和百分比:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.set_aspect('equal')
data = np.random.uniform(1, 3, 7)
wedges, texts, percs = ax.pie(data, labels=['Alkaid', 'Mizar', 'Alioth', 'Megrez', 'Phecda', 'Merak', 'Dubhe'],
                              autopct="%1.1f%%")

groups = [[0, 1, 2], [3, 4], [5, 6]]
radfraction = 0.1
for group in groups:
    ang = np.deg2rad((wedges[group[-1]].theta2 + wedges[group[0]].theta1) / 2)
    for j in group:
        center = radfraction * wedges[j].r * np.array([np.cos(ang), np.sin(ang)])
        wedges[j].set_center(center)
        texts[j].set_position(np.array(texts[j].get_position()) + center)
        percs[j].set_position(np.array(percs[j].get_position()) + center)
ax.autoscale(True)
plt.show()
Run Code Online (Sandbox Code Playgroud)

楔子成组爆炸