Okay, let's put what we've learned about Matplotlib's basic plot types into practice. In this section, we'll work through creating bar charts, histograms, and pie charts using sample data. This hands-on experience will help solidify your understanding of how and when to use each type.
First, ensure you have Matplotlib imported, typically using the standard convention:
import matplotlib.pyplot as plt
import numpy as np # We'll use NumPy for generating some sample data
Bar charts are excellent for comparing quantities across different categories. Let's imagine we want to visualize the number of units sold for different types of fruits in a small grocery stand.
Data: Suppose we have the following sales data:
Steps:
plt.bar()
function, passing the categories for the x-axis and values for the y-axis.plt.xlabel()
, plt.ylabel()
, and plt.title()
to make the plot understandable.plt.show()
.Code:
import matplotlib.pyplot as plt
# 1. Prepare the data
fruit_names = ['Apples', 'Oranges', 'Bananas', 'Grapes']
units_sold = [50, 35, 65, 42]
# 2. Create the bar chart
plt.figure(figsize=(6, 4)) # Optional: Adjust figure size
plt.bar(fruit_names, units_sold, color='#339af0') # Use a color from the blue palette
# 3. Add labels and title
plt.xlabel('Fruit Type')
plt.ylabel('Units Sold')
plt.title('Fruit Sales Comparison')
plt.xticks(rotation=45) # Rotate x-axis labels if they overlap
plt.tight_layout() # Adjust layout to prevent labels overlapping
# 4. Display the plot
plt.show()
Running this code will generate a bar chart showing the sales for each fruit type, making it easy to see that Bananas had the highest sales.
Challenge: Try modifying the code above to create a horizontal bar chart using plt.barh()
. Remember to switch the arguments and adjust the labels accordingly (plt.xlabel
becomes 'Units Sold', plt.ylabel
becomes 'Fruit Type').
Histograms help us understand the distribution of a single numerical variable by grouping data into bins and showing the frequency of observations in each bin. Let's visualize the distribution of exam scores for a class.
Data: We'll generate some random exam scores using NumPy to simulate a distribution. Let's assume scores are out of 100 and roughly normally distributed around a mean of 75.
Steps:
np.random.normal()
to create an array of scores.plt.hist()
, passing the data and optionally specifying the number of bins or letting Matplotlib decide.plt.show()
.Code:
import matplotlib.pyplot as plt
import numpy as np
# 1. Generate sample data (e.g., 100 exam scores)
np.random.seed(42) # for reproducible results
exam_scores = np.random.normal(loc=75, scale=10, size=100)
# Ensure scores are within a realistic range (e.g., 0-100)
exam_scores = np.clip(exam_scores, 0, 100)
# 2. Create the histogram
plt.figure(figsize=(7, 5))
plt.hist(exam_scores, bins=10, color='#51cf66', edgecolor='black') # Use 10 bins, green color
# 3. Add labels and title
plt.xlabel('Exam Score')
plt.ylabel('Number of Students')
plt.title('Distribution of Exam Scores')
# 4. Display the plot
plt.show()
This code will produce a histogram showing how many students scored within specific score ranges (the bins). You can experiment by changing the bins
argument (e.g., bins=5
, bins=20
) to see how it affects the appearance of the distribution.
Pie charts are used to show proportions of a whole. Let's visualize the percentage breakdown of a student's monthly expenses.
Data: Suppose the expenses are categorized as follows:
Steps:
plt.pie()
, passing the values and labels. Use autopct
to display percentages on the slices.plt.title()
. Add plt.axis('equal')
to ensure the pie chart is circular.plt.show()
.Code:
import matplotlib.pyplot as plt
# 1. Prepare the data
expense_categories = ['Rent', 'Food', 'Transport', 'Utilities', 'Entertainment']
percentages = [40, 25, 15, 10, 10]
colors = ['#748ffc', '#ff922b', '#51cf66', '#fcc419', '#f06595'] # Indigo, Orange, Green, Yellow, Pink
# 2. Create the pie chart
plt.figure(figsize=(6, 6))
plt.pie(percentages, labels=expense_categories, colors=colors,
autopct='%1.1f%%', # Format percentages to one decimal place
startangle=90) # Start the first slice at the top (90 degrees)
# 3. Add title and ensure it's circular
plt.title('Monthly Expense Breakdown')
plt.axis('equal') # Equal aspect ratio ensures a circular pie chart
# 4. Display the plot
plt.show()
This generates a pie chart illustrating how the student's budget is allocated. While useful for showing simple proportions, remember that pie charts become difficult to read when there are many categories or when the proportions are very similar. Bar charts are often a better alternative for comparisons.
You have now practiced creating the fundamental plot types covered in this chapter: bar charts for comparison, histograms for distribution, and pie charts for proportions. Feel free to modify the sample data or parameters in these examples to explore how the plots change. This experimentation is a great way to build intuition about which plot works best for different kinds of data and analytical questions.
© 2025 ApX Machine Learning