Apply code for basic pie chart.

9 b] Apply code for basic pie chart.

Pie Chart

The plt.pie(x, [explode], [labels], [autopct]) function creates a pie chart.
Important parameters:

  • x: Specifies the slice sizes.
  • explode (optional): Specifies the fraction of the radius offset for each slice. The explode-array must have the same length as the x-array.
  • labels (optional): Specifies the labels for each slice.
  • autopct (optional): Shows percentages inside the slices according to the specified format string. Example: ‘%1.1f%%’.

Example:

plt.pie([0.4, 0.3, 0.2, 0.1], explode=(0.1, 0, 0, 0), labels=['A', 'B', 
'C', 'D'])

Creating a Pie Chart for Water Usage
In this exercise, we will use a pie chart to visualize water usage. There has been a shortage of water in your locality in the past few weeks. To understand the reason behind it, generate a visual representation of water usage using pie charts.
The following are the steps to perform:

  1. Open the Exercise3.02.ipynb Jupyter Notebook from the Chapter03 folder to implement this exercise. Navigate to the path of this file and type in the following at the command line: jupyter-lab.
  2. Import the necessary modules and enable plotting within the Jupyter Notebook:
# Import statements
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

3. Use pandas to read the data located in the Datasets subfolder:

# Load dataset
data = pd.read_csv('../../Datasets/water_usage.csv')
  1. Use a pie chart to visualize water usage. Highlight one usage of your choice using the explode parameter. Show the percentages for each slice and add a title:
# Create figure
plt.figure(figsize=(8, 8), dpi=300)
# Create pie plot
plt.pie('Percentage', explode=(0, 0, 0.1, 0, 0, 0), labels='Usage', 
data=data, autopct='%.0f%%')
# Add title
plt.title('Water usage')
# Show plot
plt.show()
pie chart for water usage

Leave a Reply

Your email address will not be published. Required fields are marked *