Bar Charts in Matplotlib
Bar charts are used to represent categorical data visually, using rectangular bars. The length of each bar corresponds to the value it represents.
Creating Bar Charts
To create a bar chart, use the bar()
or barh()
function in Matplotlib.
Example: Vertical Bar Chart
import matplotlib.pyplot as plt
# Data
categories = ["Math", "Science", "English"]
scores = [85, 90, 80]
# Create vertical bar chart
plt.bar(categories, scores, color='blue')
# Add title and labels
plt.title("Student Scores")
plt.xlabel("Subjects")
plt.ylabel("Scores")
# Display the plot
plt.show()
Example: Horizontal Bar Chart
# Data
categories = ["Math", "Science", "English"]
scores = [85, 90, 80]
# Create horizontal bar chart
plt.barh(categories, scores, color='green')
# Add title and labels
plt.title("Student Scores")
plt.xlabel("Scores")
plt.ylabel("Subjects")
# Display the plot
plt.show()
Customizing Bar Charts
Matplotlib provides several parameters to style bar charts, such as:
Parameter | Description | Example Value |
---|---|---|
color | Color of the bars | 'blue' , ['red'] |
edgecolor | Border color of the bars | 'black' |
width | Width of the bars | 0.8 |
align | Alignment of the bars | 'center' , 'edge' |
Example: Customized Bar Chart
# Data
categories = ["A", "B", "C", "D"]
values = [10, 20, 15, 25]
# Create bar chart
plt.bar(categories, values, color=['red', 'blue', 'green', 'purple'], edgecolor='black', width=0.5)
# Add title and labels
plt.title("Customized Bar Chart")
plt.xlabel("Categories")
plt.ylabel("Values")
# Display the plot
plt.show()
Grouped and Stacked Bar Charts
Example: Grouped Bar Chart
import numpy as np
# Data
groups = ["Group 1", "Group 2", "Group 3"]
values1 = [20, 35, 30]
values2 = [25, 32, 34]
# Bar positions
x = np.arange(len(groups))
width = 0.35
# Create grouped bar chart
plt.bar(x - width/2, values1, width, label="Dataset 1", color='blue')
plt.bar(x + width/2, values2, width, label="Dataset 2", color='orange')
# Add title, labels, and legend
plt.title("Grouped Bar Chart")
plt.xlabel("Groups")
plt.ylabel("Values")
plt.xticks(x, groups)
plt.legend()
# Display the plot
plt.show()
Example: Stacked Bar Chart
# Data
groups = ["Group 1", "Group 2", "Group 3"]
values1 = [20, 35, 30]
values2 = [25, 32, 34]
# Create stacked bar chart
plt.bar(groups, values1, label="Dataset 1", color='blue')
plt.bar(groups, values2, bottom=values1, label="Dataset 2", color='orange')
# Add title, labels, and legend
plt.title("Stacked Bar Chart")
plt.xlabel("Groups")
plt.ylabel("Values")
plt.legend()
# Display the plot
plt.show()
Practical Examples
Example 1: Sales Comparison
# Data
months = ["Jan", "Feb", "Mar", "Apr"]
sales = [100, 150, 120, 170]
# Create bar chart
plt.bar(months, sales, color='cyan', alpha=0.7)
# Add title and labels
plt.title("Monthly Sales")
plt.xlabel("Months")
plt.ylabel("Sales (in USD)")
# Display the plot
plt.show()
Example 2: Favorite Sports
# Data
sports = ["Cricket", "Football", "Tennis", "Basketball"]
popularity = [70, 60, 40, 30]
# Create bar chart
plt.bar(sports, popularity, color=['green', 'red', 'blue', 'purple'], alpha=0.6)
# Add title and labels
plt.title("Favorite Sports")
plt.xlabel("Sports")
plt.ylabel("Popularity (%)")
# Display the plot
plt.show()
Try It Yourself
Problem 1: Compare Average Scores
Create a bar chart to compare the average scores of three classes (Class A, Class B, Class C) in Math, Science, and English.
Show Code
# Data
subjects = ["Math", "Science", "English"]
class_a = [85, 90, 80]
class_b = [88, 85, 82]
class_c = [84, 87, 86]
# Bar positions
x = np.arange(len(subjects))
width = 0.2
# Create grouped bar chart
plt.bar(x - width, class_a, width, label="Class A", color='blue')
plt.bar(x, class_b, width, label="Class B", color='green')
plt.bar(x + width, class_c, width, label="Class C", color='orange')
# Add title, labels, and legend
plt.title("Average Scores by Class")
plt.xlabel("Subjects")
plt.ylabel("Scores")
plt.xticks(x, subjects)
plt.legend()
# Display the plot
plt.show()
Problem 2: Product Sales Analysis
Create a stacked bar chart to represent the sales of two products (Product A and Product B) in three regions (North, South, East).
Show Code
# Data
regions = ["North", "South", "East"]
product_a = [200, 250, 300]
product_b = [150, 200, 250]
# Create stacked bar chart
plt.bar(regions, product_a, label="Product A", color='skyblue')
plt.bar(regions, product_b, bottom=product_a, label="Product B", color='lightgreen')
# Add title, labels, and legend
plt.title("Product Sales by Region")
plt.xlabel("Regions")
plt.ylabel("Sales (in USD)")
plt.legend()
# Display the plot
plt.show()
Bar charts are an excellent way to visualize categorical data. Use the examples and customization options above to create compelling bar charts for your datasets.