How to Set Figure Size in Matplotlib: Simple Guide
To set the figure size in Matplotlib, use the
figsize parameter inside plt.figure() or plt.subplots(). The figsize takes a tuple of width and height in inches, for example, figsize=(8, 6) sets the figure width to 8 inches and height to 6 inches.Syntax
The figsize parameter controls the size of the figure in inches. It is used as a tuple (width, height) where both values are numbers representing inches.
You can set it when creating a figure with plt.figure(figsize=(width, height)) or when creating subplots with plt.subplots(figsize=(width, height)).
python
import matplotlib.pyplot as plt plt.figure(figsize=(width, height)) # width and height are floats or ints in inches # or fig, ax = plt.subplots(figsize=(width, height))
Example
This example shows how to create a plot with a figure size of 8 inches wide and 4 inches tall. The plot will display a simple line graph.
python
import matplotlib.pyplot as plt plt.figure(figsize=(8, 4)) plt.plot([1, 2, 3, 4], [10, 20, 25, 30]) plt.title('Line Plot with Custom Figure Size') plt.xlabel('X axis') plt.ylabel('Y axis') plt.show()
Output
A plot window opens showing a line graph with a wide rectangular shape (8x4 inches).
Common Pitfalls
- Not using
figsizeinside the figure creation function causes the default size to be used, which might be too small or large. - Passing
figsizeas a single number or wrong type instead of a tuple will cause errors. - Changing figure size after plotting without recreating the figure does not resize the plot.
python
import matplotlib.pyplot as plt # Wrong: figsize as single number (causes error) # plt.figure(figsize=8) # This will raise a TypeError # Correct way: plt.figure(figsize=(8, 6)) plt.plot([1, 2, 3], [4, 5, 6]) plt.show()
Output
A plot window opens with a figure sized 8x6 inches.
Quick Reference
Use this quick guide to remember how to set figure size in Matplotlib:
| Action | Code Example | Description |
|---|---|---|
| Create figure with size | plt.figure(figsize=(width, height)) | Sets figure size in inches when creating a figure |
| Create subplots with size | fig, ax = plt.subplots(figsize=(width, height)) | Sets figure size for subplots |
| Width and height units | figsize=(8, 6) | Width and height are in inches |
| Common mistake | plt.figure(figsize=8) | Wrong: figsize must be a tuple |
Key Takeaways
Set figure size using the figsize parameter as a tuple (width, height) in inches.
Use figsize inside plt.figure() or plt.subplots() when creating the plot.
Always pass figsize as a tuple, not a single number.
Changing figure size after plotting requires creating a new figure.
Proper figure size helps make plots clear and readable.