Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

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.

Students Enrolled in Different Courses 856510050 JavaPythonWeb Dev.Data Sci. Number of Students
Figure 1: A bar chart comparing student enrolment across four courses.

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()
ParameterDescription
categoriesCategory names displayed along the X-axis.
valuesNumerical values that determine the bar heights.
plt.bar()Creates a vertical bar chart.
plt.show()Displays the created chart.
Tip: Categories and values should contain the same number of items so that every category has a corresponding bar.

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.
Students Enrolled in Courses 856510050JavaPythonWeb Dev.Data Sci. Number of Students
Figure 2: Expected output of the Python code shown above.

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()
ParameterDescriptionExample
colorSets the fill colour of bars.color="orange"
widthControls the width of vertical bars.width=0.6
edgecolorSets the border colour.edgecolor="black"
alphaControls bar transparency.alpha=0.8
Course Enrolment by Colour JavaPythonWebData Science
Figure 3: Each course uses a different bar colour and a black border.

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.

Employees in Each Department DevelopmentTestingHRMarketing 010203040
Figure 4: Horizontal bars compare employee counts across departments.

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()
Tip: bar_label() is available in modern Matplotlib versions. The padding parameter controls the space between each bar and its label.
Monthly Sales 120150100180JanFebMarApr
Figure 5: Sales values are displayed above their corresponding bars.

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.
Product Sales Comparison LaptopMobileTablet 2025 2026
Figure 6: Side-by-side bars compare product sales for 2025 and 2026.

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.

Monthly Sales by Channel JanFebMarApr Online Sales Store Sales
Figure 7: Each bar is divided into online and store sales segments.

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.

FunctionPurpose
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()
Student Marks by Subject MathsScienceEnglishComputer Marks
Figure 8: A formatted bar chart with a title, axis labels, grid lines, and legend.

11. Bar Chart vs Histogram

Bar charts and histograms both use rectangular bars, but they represent different types of data and answer different questions.

Bar Chart Histogram Separate categories Continuous intervals
Figure 9: Bar charts compare categories; histograms show the distribution of numerical data.
FeatureBar ChartHistogram
Data TypeCategorical data.Continuous numerical data.
BarsUsually have gaps.Usually touch each other.
PurposeCompare values across categories.Show the distribution of values.
Matplotlib Functionplt.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()
ParameterDescription
product_sales.pngName and format of the saved chart.
dpi=300Sets the output resolution.
bbox_inches="tight"Adjusts the saved bounding box to fit chart content.
Important: Save the figure before calling plt.show() in workflows where displaying the figure may close or clear it.
Product Sales LaptopMobileTablet
Figure 10: Example appearance of the saved product_sales.png file.

13. Common Mistakes While Creating Bar Charts

Understanding common issues helps you write correct Matplotlib code.

Common MistakeSolution
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.

  1. Create a list containing six month names.
  2. Create a list containing sales values for those months.
  3. Use plt.bar() to create a vertical bar chart.
  4. Set the bar colour to green.
  5. Add a chart title and axis labels.
  6. Display sales values above the bars.
  7. Enable horizontal grid lines.
  8. 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:

  1. What is a bar chart?
  2. Which Matplotlib function creates a vertical bar chart?
  3. What is the difference between bar() and barh()?
  4. Which parameter controls the width of vertical bars?
  5. How can you set different colours for individual bars?
  6. What is the purpose of the edgecolor parameter?
  7. How can you display values above bars?
  8. What is a grouped bar chart?
  9. What is the purpose of the bottom parameter in a stacked bar chart?
  10. 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.