Home > Back-end >  Python Matplotlib Pie chart merge two slices with identical titles together
Python Matplotlib Pie chart merge two slices with identical titles together

Time:12-10

I'm doing a matplotlib project with pie charts and would like to merge two slices in a pie chart with identical titles together to form one big slice with the same title.

enter image description here

However, matplotlib just leaves the slices seperated, even though they have the same title.

May I know how I can do that? Thanks.

And yes, some code.

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

CodePudding user response:

Preprocess your titles and values then draw the chart:
We loop through the list0 (the values) and list1 (the titles) together, and make each of the titles as the key of the dictionary then add the corresponding value from the list0 to that key. So the values of the titles with same name will be added to one and the same {key: val} in the dictionary.
When all the items are examined, we return the list of the keys of the dictionary as the titles and the corresponding values as the values of the charts for each title.

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()

Output:
enter image description here

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.

CodePudding user response:

In my opinion, it would be fastest to add code that aggregates values with the same title.

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()

CodePudding user response:

this can do,

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()

Output:

enter image description here

  • Related