Drawing pie charts

Let's see how to plot pie charts. This is useful when you want to visualize the percentages of a set of labels in a group.

How to do it…

  1. Create a new Python file, and import the following packages:
    import numpy as np
    import matplotlib.pyplot as plt 
  2. Define the labels and values:
    # Labels and corresponding values in counter clockwise direction
    data = {'Apple': 26, 
            'Mango': 17,
            'Pineapple': 21, 
            'Banana': 29, 
            'Strawberry': 11}
  3. Define the colors for visualization:
    # List of corresponding colors
    colors = ['orange', 'lightgreen', 'lightblue', 'gold', 'cyan']
  4. Define a variable to highlight a section of the pie chart by separating it from the rest. If you don't want to highlight any section, set all the values to 0:
    # Needed if we want to highlight a section
    explode = (0, 0, 0, 0, 0)  
  5. Plot the pie chart. Note that if you use Python 3, you should use list(data.values()) in the following function call:
    # Plot the pie chart
    plt.pie(data.values(), explode=explode, labels=data.keys(), 
            colors=colors, autopct='%1.1f%%', shadow=False, startangle=90)
    
    # Aspect ratio of the pie chart, 'equal' indicates tht we 
    # want it to be a circle
    plt.axis('equal')
    
    plt.show()
  6. The full code is in the pie_chart.py file that's already provided to you. If you run this code, you will see the following figure:
    How to do it…

    If you change the explode array to (0, 0.2, 0, 0, 0), then it will highlight the Strawberry section. You will see the following figure:

    How to do it…
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.140.108