Python Matplotlib 饼图将两个标题相同的切片合并在一起

Python Matplotlib Pie chart merge two slices with identical titles together

我正在做一个带有饼图的 matplotlib 项目,想将饼图中两个标题相同的切片合并在一起,形成一个标题相同的大切片

然而,matplotlib 只是将切片分开,即使它们具有相同的标题。

我可以知道我该怎么做吗?谢谢

是的,一些代码。

from matplotlib import pyplot as plt
list0 = [1,2,3]
list1 = ["apple", "banana", "banana"]
plt.pie(list0, labels = list1)
plt.show()

这个可以,

from matplotlib import pyplot as plt

list0 = [1, 2, 3]
list1 = ["apple", "banana", "banana"]

sourceDict = {}
for i, j in zip(list1, list0):
    if not i in sourceDict:
        sourceDict.update({i: j})
    else:
        sourceDict[i] += j

plt.pie(sourceDict.values(), labels=sourceDict.keys())
plt.show()

输出:

在我看来,添加聚合具有相同标题的值的代码是最快的。

from matplotlib import pyplot as plt
list0 = [1,2,3]
list1 = ["apple", "banana", "banana"]

m = {k:sum([list0[i] for i, l in enumerate(list1) if l == k ]) for k in set(list1)}

plt.pie(m.values(), labels = m.keys())
plt.show()

预处理您的标题和值然后绘制图表:
我们一起循环 list0 (values) 和 list1 (titles),并使每个 titles 成为 key dictionary 然后将 list0 中对应的 value 添加到 key。所以同名的标题的值将被添加到字典中一个相同的{key: val}
当检查所有项目时,我们 return 字典的 keys 的列表作为 titles 和相应的 values 作为每个 [= 图表的值25=].

from matplotlib import pyplot as plt

def merge_slices(list0, list1):
    from collections import defaultdict
    dict_slices = defaultdict(lambda: 0)
    for val, title in zip(list0, list1):
        dict_slices[title] += val
    return list(dict_slices.values()), list(dict_slices.keys())

if __name__ == "__main__":
    list0 = [1,2,3]
    list1 = ["apple", "banana", "banana"]
    merged_list0, merged_list1 = merge_slices(list0 ,list1)
    plt.pie(merged_list0, labels = merged_list1)
    plt.show()

输出:

defaultdict will create a key and set a default value for the keys which are not in the dictionary. In the snippet above, we set it in a way that, it will set 0 for the key which wasn't in the dictionary before.