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

Figure Dimensions and Resolution

In this lesson, you will learn how to control the width, height, and resolution of Matplotlib figures. You will also understand how figure dimensions and DPI affect the appearance and quality of charts.

1. Learning Objectives

By the end of this lesson, you will be able to:

  • Understand Figure dimensions in Matplotlib.
  • Set Figure width and height using figsize.
  • Understand the meaning of DPI.
  • Configure Figure resolution.
  • Calculate the approximate pixel dimensions of a Figure.
  • Understand the difference between screen display and saved image resolution.
  • Choose suitable dimensions and resolution for different outputs.
  • Export charts with appropriate image quality.

2. What Are Figure Dimensions?

Figure dimensions define the physical width and height of a Matplotlib Figure. These dimensions determine how much space is available for charts, titles, labels, legends, and other visualization elements.

Matplotlib uses inches as the standard unit for Figure dimensions. We configure these dimensions using the figsize parameter.

Example: Sales Report

Suppose Omkar wants to create a monthly sales report. A wider Figure can provide enough space for month labels and a detailed chart. A smaller Figure may be suitable for a simple visualization.

The selected dimensions should match the purpose of the visualization and the available display or document space.

Matplotlib Figure Width = 10 inches Figure Width Height
Figure 1: Figure dimensions represent the width and height of the canvas.

3. Setting Figure Dimensions Using figsize

Matplotlib provides the figsize parameter to set the dimensions of a Figure. It accepts a tuple containing width and height in inches.

Syntax

fig, ax = plt.subplots(figsize=(width, height))

Example

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10, 5))

ax.plot([1, 2, 3, 4], [10, 20, 15, 30])

ax.set_title("Sales Report")

plt.show()

Explanation:

  • fig: Stores the Figure object.
  • ax: Stores the Axes object.
  • figsize=(10, 5): Sets width to 10 inches and height to 5 inches.
  • ax.plot(): Creates a line chart.
  • plt.show(): Displays the visualization.
Tip: The figsize parameter accepts values in inches, not pixels. The final pixel dimensions also depend on DPI.

4. Understanding Different Figure Sizes

Different visualizations may require different Figure dimensions. The following examples demonstrate common size configurations.

Figure Size Orientation Suitable Use
(6, 4) Landscape Small charts and basic examples.
(10, 5) Landscape Reports and wider visualizations.
(12, 6) Landscape Large charts and dashboards.
(5, 8) Portrait Tall charts and vertical layouts.
(8, 8) Square Square plots and balanced visualizations.

Example: Compare Figure Sizes

import matplotlib.pyplot as plt

# Small Figure
fig1, ax1 = plt.subplots(figsize=(6, 4))
ax1.set_title("Small Figure")

# Large Figure
fig2, ax2 = plt.subplots(figsize=(12, 6))
ax2.set_title("Large Figure")

plt.show()
Small (6, 4) Large Figure (12, 6) Portrait (5, 8) Small canvas Wide canvas Tall canvas
Figure 2: Different Figure dimensions for different visualization requirements.

5. What Is DPI in Matplotlib?

DPI stands for Dots Per Inch. It defines how many pixels are used for each inch of a Figure when it is rendered.

A higher DPI generally produces a larger pixel image for the same physical Figure size. It is especially important when saving charts for documents, presentations, and printing.

Example: Setting DPI

import matplotlib.pyplot as plt

fig, ax = plt.subplots(
    figsize=(8, 5),
    dpi=100
)

ax.plot([1, 2, 3, 4], [10, 20, 15, 30])

ax.set_title("DPI Example")

plt.show()

Here, the Figure is configured with a resolution of 100 DPI. The exact display appearance also depends on the backend and the environment where the chart is rendered.

Lower DPI Higher DPI Fewer pixels per inch More pixels per inch
Figure 3: Conceptual illustration of pixel density at different DPI settings.
Tip: DPI affects the pixel resolution of a rendered Figure. It does not change the physical figsize values.

6. Understanding Pixel Dimensions

We can calculate the approximate pixel dimensions of a Figure using its size in inches and its DPI value.

Formula

Width in Pixels = Figure Width in Inches × DPI

Height in Pixels = Figure Height in Inches × DPI

Example Calculation

Suppose we create a Figure with a width of 8 inches, a height of 5 inches, and a DPI of 100.

Width  = 8 × 100 = 800 pixels

Height = 5 × 100 = 500 pixels

Final Image Size = 800 × 500 pixels

Therefore, the approximate raster output dimensions are 800 pixels wide and 500 pixels high.

Figure Size DPI Approximate Pixel Dimensions
(8, 5) 100 800 × 500
(8, 5) 150 1200 × 750
(8, 5) 200 1600 × 1000
(10, 6) 100 1000 × 600
(10, 6) 300 3000 × 1800
Remember: These calculations describe raster image dimensions. Vector formats such as SVG and PDF do not have a fixed pixel resolution in the same way.

7. Difference Between Figure Size and DPI

Figure size and DPI are related, but they control different properties of a visualization.

Figure Size DPI
Controls the physical width and height. Controls pixel density per inch.
Specified using figsize. Specified using dpi.
Measured in inches. Measured in dots per inch.
Changes the canvas dimensions. Changes raster rendering resolution.
Example: figsize=(10, 5). Example: dpi=150.

8. Setting Figure DPI and Save DPI

Matplotlib allows us to configure DPI when creating a Figure and also specify a separate DPI value when saving an image.

Example: Save a High-Resolution Image

import matplotlib.pyplot as plt

fig, ax = plt.subplots(
    figsize=(8, 5),
    dpi=100
)

ax.plot(
    [1, 2, 3, 4],
    [10, 20, 15, 30],
    marker="o"
)

ax.set_title("High Resolution Chart")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")

# Save the chart at 300 DPI
fig.savefig(
    "high_resolution_chart.png",
    dpi=300,
    bbox_inches="tight"
)

plt.show()

The Figure is created with a DPI of 100, while the PNG file is saved using 300 DPI.

Tip: The dpi argument of savefig() can be used to control the raster resolution of the exported image separately from the Figure's initial DPI.

9. Choosing Suitable Dimensions and Resolution

Different output requirements need different Figure dimensions and resolution settings.

Use Case Example Figure Size Example DPI
Basic learning examples (6, 4) 100
Presentation charts (10, 5) 150
Report images (8, 5) 200
High-resolution raster export (10, 6) 300
Square visualizations (8, 8) 150
Important: These are example configurations, not fixed requirements. Choose dimensions and DPI according to the target document, display, and export format.

10. Adjusting Layout for Figure Dimensions

When we create a Figure with titles, axis labels, and legends, some elements may overlap or extend outside the available canvas. Matplotlib provides layout tools to help arrange these elements.

Using tight_layout()

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 5))

ax.plot([1, 2, 3, 4], [10, 20, 15, 30])

ax.set_title("Student Performance Report")
ax.set_xlabel("Student Number")
ax.set_ylabel("Marks")

fig.tight_layout()

plt.show()

The tight_layout() method automatically adjusts subplot parameters to reduce overlapping between plot elements.

Using constrained_layout

import matplotlib.pyplot as plt

fig, ax = plt.subplots(
    figsize=(8, 5),
    layout="constrained"
)

ax.plot([1, 2, 3, 4], [10, 20, 15, 30])

ax.set_title("Student Performance")

plt.show()

The constrained layout engine helps arrange Axes and decorations to reduce overlaps.

Tip: Choose one layout approach for a Figure instead of unnecessarily combining multiple layout adjustments.

11. Complete Example: Figure Dimensions and Resolution

Let's create a complete student performance visualization with custom dimensions, DPI, labels, grid lines, and save settings.

Student Performance Chart

import matplotlib.pyplot as plt

# Sample student data
students = ["Amit", "Rahul", "Priya", "Sneha", "Om"]
marks = [75, 82, 90, 68, 95]

# Create Figure with dimensions and DPI
fig, ax = plt.subplots(
    figsize=(10, 5),
    dpi=100
)

# Create chart
ax.bar(
    students,
    marks,
    color="steelblue",
    label="Student Marks"
)

# Add chart information
ax.set_title("Student Performance Report")
ax.set_xlabel("Students")
ax.set_ylabel("Marks")

# Configure Y-axis
ax.set_ylim(0, 100)

# Add grid and legend
ax.grid(axis="y", linestyle="--", alpha=0.5)
ax.legend()

# Adjust layout
fig.tight_layout()

# Save at 300 DPI
fig.savefig(
    "student_performance.png",
    dpi=300,
    bbox_inches="tight"
)

# Display chart
plt.show()

This example creates a 10 × 5 inch Figure, displays a student performance bar chart, and exports the image at 300 DPI.

Student Performance Report Amit Rahul Priya Sneha Om Students Marks
Figure 4: Conceptual preview of the student performance chart.

12. Common Mistakes in Figure Dimensions and Resolution

Common Mistake Correct Approach
Providing pixel values directly to figsize. Use width and height in inches.
Confusing DPI with Figure size. Remember that DPI controls pixels per inch.
Using very high DPI unnecessarily. Select DPI based on output requirements.
Ignoring overlapping titles and labels. Use suitable layout adjustments.
Expecting vector files to have fixed raster dimensions. Understand the difference between raster and vector formats.
Saving an image without checking its dimensions. Configure savefig() DPI and inspect the exported image.

13. Classroom Practical Activity

Activity: Create a High-Resolution Sales Chart

Create a Matplotlib Figure that displays monthly sales data. Use the following sample data:

months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [120, 150, 180, 140, 220]

Complete the following tasks:

  1. Import Matplotlib using pyplot.
  2. Create a Figure with figsize=(10, 5).
  3. Set the Figure DPI to 100.
  4. Create a line chart using the sample data.
  5. Add a suitable chart title and axis labels.
  6. Configure the grid and legend.
  7. Use tight_layout() to adjust the chart layout.
  8. Save the chart as a PNG image at 300 DPI.
  9. Calculate the approximate pixel dimensions of the saved image.

Practice Questions

  1. What are Figure dimensions in Matplotlib?
  2. Which parameter controls the width and height of a Figure?
  3. What unit is used by figsize?
  4. What does DPI stand for?
  5. How do you calculate the pixel width of a Figure?
  6. What is the difference between Figure size and DPI?
  7. How can you save a chart at 300 DPI?
  8. What is the purpose of tight_layout()?
  9. What is the difference between raster and vector image formats?

Summary

In this lesson, you learned how to configure Figure dimensions and resolution in Matplotlib. Figure dimensions control the physical size of the canvas, while DPI controls the pixel density used when rendering raster output.

You also explored how to calculate approximate pixel dimensions, configure DPI during Figure creation, save high-resolution images, and adjust chart layouts using Matplotlib layout tools.

  • figsize controls Figure width and height in inches.
  • DPI means Dots Per Inch.
  • Pixel width = Figure width × DPI.
  • Pixel height = Figure height × DPI.
  • savefig() can use a separate DPI setting for exported images.
  • tight_layout() helps reduce overlapping chart elements.
  • Vector formats such as SVG and PDF are resolution-independent in their scaling.

In the next lesson, we will learn how to save Matplotlib visualizations in different image and document formats.