Bar Charts in Matplotlib
In this lesson, you will learn how to create vertical and horizontal bar charts using Matplotlib. You will also explore bar colours, widths, value labels, grouped bars, stacked bars, and chart formatting.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Understand what a bar chart is and when it is used.
- Create vertical bar charts using the bar() function.
- Create horizontal bar charts using the barh() function.
- Customize bar colours, widths, borders, and transparency.
- Display numerical values on bars.
- Create grouped and stacked bar charts.
- Add titles, axis labels, legends, and grid lines.
- Save bar charts in different file formats.
2. What Is a Bar Chart?
A bar chart is a graphical representation of data that uses rectangular bars to compare values across different categories. The height or length of each bar represents the value of that category.
Matplotlib provides bar() for vertical bars and barh() for horizontal bars.
Example: Students Enrolled in Different Courses
An institute wants to compare student enrolment in Java, Python, Web Development, and Data Science courses. Each course is a category, and the number of students is its value.
3. Basic Syntax of the bar() Function
The bar() function accepts category names and their corresponding numerical values.
Syntax
import matplotlib.pyplot as plt
plt.bar(categories, values)
plt.show()
| Parameter | Description |
|---|---|
| categories | Category names displayed along the X-axis. |
| values | Numerical values that determine the bar heights. |
| plt.bar() | Creates a vertical bar chart. |
| plt.show() | Displays the created chart. |
4. Creating Your First Vertical Bar Chart
Let's compare the number of students enrolled in different programming courses.
Example: Course Enrolment
import matplotlib.pyplot as plt
courses = ["Java", "Python", "Web Development", "Data Science"]
students = [85, 65, 100, 50]
plt.bar(courses, students)
plt.title("Students Enrolled in Courses")
plt.xlabel("Courses")
plt.ylabel("Number of Students")
plt.show()
Explanation:
- courses contains the category names for the X-axis.
- students contains values that determine bar heights.
- bar() creates one vertical bar for each course.
- title(), xlabel(), and ylabel() add chart information.
- show() displays the chart.
5. Customizing Bar Colours and Widths
You can customize bar colours, widths, borders, and transparency.
Example: Different Colours for Each Bar
import matplotlib.pyplot as plt
courses = ["Java", "Python", "Web", "Data Science"]
students = [85, 65, 100, 50]
bar_colors = ["royalblue", "orange", "seagreen", "tomato"]
plt.bar(
courses,
students,
color=bar_colors,
width=0.6,
edgecolor="black"
)
plt.title("Course Enrolment by Colour")
plt.xlabel("Courses")
plt.ylabel("Students")
plt.show()
| Parameter | Description | Example |
|---|---|---|
| color | Sets the fill colour of bars. | color="orange" |
| width | Controls the width of vertical bars. | width=0.6 |
| edgecolor | Sets the border colour. | edgecolor="black" |
| alpha | Controls bar transparency. | alpha=0.8 |
6. Creating a Horizontal Bar Chart
A horizontal bar chart displays categories along the Y-axis and values along the X-axis. It is useful when category names are long. Use barh() to create it.
Example: Employee Count by Department
import matplotlib.pyplot as plt
departments = ["Development", "Testing", "HR", "Marketing"]
employees = [40, 25, 12, 18]
plt.barh(departments, employees, color="teal")
plt.title("Employees in Each Department")
plt.xlabel("Number of Employees")
plt.ylabel("Department")
plt.show()
Explanation: barh() creates horizontal bars. Department names appear on the Y-axis, and employee counts determine bar lengths.
7. Adding Value Labels to Bars
The bar_label() method displays numerical values on or near each bar.
Example: Displaying Values Above Bars
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr"]
sales = [120, 150, 100, 180]
fig, ax = plt.subplots()
bars = ax.bar(months, sales, color="cornflowerblue")
ax.bar_label(bars, padding=3)
ax.set_title("Monthly Sales")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")
plt.show()
8. Creating a Grouped Bar Chart
A grouped bar chart places multiple bars side by side for each category. It is useful for comparing related data series, such as sales from different years.
Example: Comparing Sales in Two Years
import matplotlib.pyplot as plt
import numpy as np
products = ["Laptop", "Mobile", "Tablet"]
sales_2025 = [50, 80, 40]
sales_2026 = [65, 70, 55]
x = np.arange(len(products))
width = 0.35
fig, ax = plt.subplots()
ax.bar(x - width / 2, sales_2025, width, label="2025")
ax.bar(x + width / 2, sales_2026, width, label="2026")
ax.set_title("Product Sales Comparison")
ax.set_xlabel("Products")
ax.set_ylabel("Sales")
ax.set_xticks(x)
ax.set_xticklabels(products)
ax.legend()
plt.show()
- np.arange() creates positions for product categories.
- width defines the width of each bar.
- x - width / 2 places the first series to the left.
- x + width / 2 places the second series to the right.
- legend() identifies the two years.
9. Creating a Stacked Bar Chart
A stacked bar chart displays multiple data series on top of one another. It helps compare the total value and the contribution of each series. The bottom parameter sets the starting position of a series.
Example: Monthly Online and Store Sales
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr"]
online_sales = [30, 40, 35, 50]
store_sales = [20, 25, 30, 25]
plt.bar(months, online_sales, label="Online Sales")
plt.bar(
months,
store_sales,
bottom=online_sales,
label="Store Sales"
)
plt.title("Monthly Sales by Channel")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.show()
The second bar() call uses bottom=online_sales. This places the store sales segment above the online sales segment for each month.
10. Adding Titles, Axis Labels, Grid, and Legend
Titles and axis labels explain the chart. Grid lines make values easier to read, and legends identify different data series.
| Function | Purpose |
|---|---|
| plt.title() | Adds a chart title. |
| plt.xlabel() | Adds the X-axis label. |
| plt.ylabel() | Adds the Y-axis label. |
| plt.grid() | Displays grid lines. |
| plt.legend() | Displays labels for data series. |
Example: Formatting a Bar Chart
import matplotlib.pyplot as plt
subjects = ["Maths", "Science", "English", "Computer"]
marks = [85, 78, 90, 95]
plt.bar(subjects, marks, color="slateblue", label="Marks")
plt.title("Student Marks by Subject")
plt.xlabel("Subjects")
plt.ylabel("Marks")
plt.ylim(0, 100)
plt.grid(axis="y", linestyle="--", alpha=0.5)
plt.legend()
plt.show()
11. Bar Chart vs Histogram
Bar charts and histograms both use rectangular bars, but they represent different types of data and answer different questions.
| Feature | Bar Chart | Histogram |
|---|---|---|
| Data Type | Categorical data. | Continuous numerical data. |
| Bars | Usually have gaps. | Usually touch each other. |
| Purpose | Compare values across categories. | Show the distribution of values. |
| Matplotlib Function | plt.bar() | plt.hist() |
12. Saving a Bar Chart
You can save a Matplotlib bar chart using savefig(). Common formats include PNG, JPEG, SVG, and PDF.
Example: Saving a Bar Chart
import matplotlib.pyplot as plt
products = ["Laptop", "Mobile", "Tablet"]
sales = [50, 80, 40]
plt.bar(products, sales, color="cornflowerblue")
plt.title("Product Sales")
plt.savefig(
"product_sales.png",
dpi=300,
bbox_inches="tight"
)
plt.show()
| Parameter | Description |
|---|---|
| product_sales.png | Name and format of the saved chart. |
| dpi=300 | Sets the output resolution. |
| bbox_inches="tight" | Adjusts the saved bounding box to fit chart content. |
13. Common Mistakes While Creating Bar Charts
Understanding common issues helps you write correct Matplotlib code.
| Common Mistake | Solution |
|---|---|
| Categories and values have different lengths. | Make sure both sequences contain the same number of items. |
| Category names overlap. | Use a horizontal bar chart or rotate tick labels. |
| Bars are too wide or narrow. | Adjust the width parameter. |
| Grouped bars overlap. | Use suitable positions and bar widths. |
| Stacked bars start at the wrong position. | Provide the correct bottom values. |
| Chart is not displayed. | Call plt.show() in a normal Python script. |
14. Practical Activity
Task: Create a Monthly Sales Bar Chart
Create a bar chart to compare shop sales across six months.
- Create a list containing six month names.
- Create a list containing sales values for those months.
- Use plt.bar() to create a vertical bar chart.
- Set the bar colour to green.
- Add a chart title and axis labels.
- Display sales values above the bars.
- Enable horizontal grid lines.
- Save the chart as monthly_sales.png.
Starter Code
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
sales = [120, 150, 100, 180, 160, 200]
# Create your bar chart here
plt.show()
15. Practice Questions
Test your understanding of Matplotlib bar charts:
- What is a bar chart?
- Which Matplotlib function creates a vertical bar chart?
- What is the difference between bar() and barh()?
- Which parameter controls the width of vertical bars?
- How can you set different colours for individual bars?
- What is the purpose of the edgecolor parameter?
- How can you display values above bars?
- What is a grouped bar chart?
- What is the purpose of the bottom parameter in a stacked bar chart?
- Which function is used to save a bar chart?
Summary
In this lesson, you learned how to create bar charts using Matplotlib. You explored vertical and horizontal bars, bar colours and widths, value labels, grouped bars, stacked bars, and chart formatting.
- Use plt.bar() to create vertical bar charts.
- Use plt.barh() to create horizontal bar charts.
- Use color to customize bar colours.
- Use width to control the width of vertical bars.
- Use edgecolor to set bar borders.
- Use bar_label() to display values on bars.
- Use multiple bar() calls to create grouped charts.
- Use bottom to create stacked bar charts.
- Use title(), xlabel(), ylabel(), grid(), and legend() to format charts.
- Use savefig() to save the chart.