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.
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.
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()
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.
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 |
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.
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 |
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.
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.
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:
- Import Matplotlib using pyplot.
- Create a Figure with figsize=(10, 5).
- Set the Figure DPI to 100.
- Create a line chart using the sample data.
- Add a suitable chart title and axis labels.
- Configure the grid and legend.
- Use tight_layout() to adjust the chart layout.
- Save the chart as a PNG image at 300 DPI.
- Calculate the approximate pixel dimensions of the saved image.
Practice Questions
- What are Figure dimensions in Matplotlib?
- Which parameter controls the width and height of a Figure?
- What unit is used by figsize?
- What does DPI stand for?
- How do you calculate the pixel width of a Figure?
- What is the difference between Figure size and DPI?
- How can you save a chart at 300 DPI?
- What is the purpose of tight_layout()?
- 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.