Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Setting the size of the plotting canvas in Matplotlib
To set the size of the plotting canvas in Matplotlib, you can control the figure dimensions using several approaches. The figure size determines how large your plot will appear when displayed or saved.
Using rcParams (Global Setting)
The most common approach is to set global parameters that affect all subsequent plots ?
import numpy as np
import matplotlib.pyplot as plt
# Set figure size globally
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create data points
x = np.linspace(-2, 2, 100)
y = np.sin(x)
# Create the plot
plt.plot(x, y)
plt.title("Sine Wave with Custom Canvas Size")
plt.show()
Using plt.figure() Method
You can set the size for individual figures using the figsize parameter ?
import numpy as np
import matplotlib.pyplot as plt
# Create figure with specific size
plt.figure(figsize=(10, 6))
x = np.linspace(-2, 2, 100)
y = np.cos(x)
plt.plot(x, y, 'r-', linewidth=2)
plt.title("Cosine Wave with Individual Figure Size")
plt.grid(True, alpha=0.3)
plt.show()
Using Subplots with Custom Size
When creating subplots, you can specify the figure size directly ?
import numpy as np
import matplotlib.pyplot as plt
# Create subplots with custom figure size
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
x = np.linspace(0, 4*np.pi, 100)
# First subplot
ax1.plot(x, np.sin(x), 'b-')
ax1.set_title("Sine Wave")
# Second subplot
ax2.plot(x, np.cos(x), 'g-')
ax2.set_title("Cosine Wave")
plt.tight_layout()
plt.show()
Comparison of Methods
| Method | Scope | Best For |
|---|---|---|
rcParams |
Global (all plots) | Consistent sizing across notebook |
plt.figure(figsize=) |
Single figure | Individual plot customization |
plt.subplots(figsize=) |
Subplot arrangement | Multi-panel figures |
Key Points
- figsize takes a tuple (width, height) in inches
-
figure.autolayout=Trueautomatically adjusts spacing - Use
plt.tight_layout()for better subplot spacing - Default figure size is typically (6.4, 4.8) inches
Conclusion
Use rcParams for consistent global sizing, plt.figure(figsize=) for individual plots, or plt.subplots(figsize=) for multi-panel figures. The figsize parameter controls canvas dimensions in inches.
Advertisements
