【发布时间】:2022-01-04 20:47:57
【问题描述】:
我真的很喜欢 matplotlib 饼图上的“爆炸”选项。我希望能够“分组爆炸”。我正在绘制很多属于 3 或 4 类的小切片。我想把所有的小切片一起爆炸,成组。
我认为这并不完全清楚,所以我呼吁我非常缺乏绘制基本形状的能力,并制作了这张图片来展示我正在尝试做的事情:
请注意各组之间没有阴影的小间隙。
这可能吗?
非常感谢,亚历克斯
【问题讨论】:
标签: python matplotlib pie-chart
我真的很喜欢 matplotlib 饼图上的“爆炸”选项。我希望能够“分组爆炸”。我正在绘制很多属于 3 或 4 类的小切片。我想把所有的小切片一起爆炸,成组。
我认为这并不完全清楚,所以我呼吁我非常缺乏绘制基本形状的能力,并制作了这张图片来展示我正在尝试做的事情:
请注意各组之间没有阴影的小间隙。
这可能吗?
非常感谢,亚历克斯
【问题讨论】:
标签: python matplotlib pie-chart
我不知道有任何直接的方法来指定分组的分解饼图,但是使用补丁来重绘带有像这样的组的饼图非常简单
# 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)
这可能会导致类似
当然,您可以简单地根据您的数据计算所需的 theta 角度,而不是使用预先计算的角度。
【讨论】:
这是@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()
【讨论】: