Search code examples
pythonpie-chart

Sorting counter dictionary to get list of keys and values


I have a list of values and i would like to plot the values and its frequency on a pie chart that is, i would like to plot only the two highest values on a piechart

Value_list = [1, 3, 2, 4, 5, 1, 1, 1, 1, 1, 3, 3, 3, 2, 2, 2, 5, 2, 2, 2, 2, 1, 1]

Solution

  • You can do this with matplotlib and collections.Counter,

    value_list = [1, 3, 2, 4, 5, 1, 1, 1, 1, 1, 3, 3, 3, 2, 2, 5, 2, 2, 2, 2, 1, 1]
    
    import matplotlib.pyplot as plt
    from collections import Counter
    
    most_common_2 = Counter(value_list).most_common(2) # taking most 2 common values
    
    labels = []
    values = []
    for label, value in most_common_2:
        labels.append(label)
        values.append(value)
    
    fig1, ax1 = plt.subplots()
    ax1.pie(values, labels=labels, autopct='%1.1f%%',
            shadow=True, startangle=90)
    ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
    
    plt.show()
    

    Result: enter image description here