Search code examples
pythonmatplotlibpie-chart

Python Matplotlib Pie chart merge two slices with identical titles together


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

Solution

  • 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.