Matplotlib is a powerful Python library for creating visualizations. While generating plots is easy, controlling their size is crucial for readability and presentation. This article explores various methods to adjust Matplotlib plot sizes.
Table of Contents
- Setting
figsize
infigure()
- Modifying
rcParams
for Global Changes - Using
set_figheight()
andset_figwidth()
- Using
set_size_inches()
- Figure Formats and
savefig()
1. Setting figsize
in figure()
The simplest method is specifying the figsize
argument in matplotlib.pyplot.figure()
. figsize
takes a tuple (width, height) in inches.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig = plt.figure(figsize=(10, 6)) # 10 inches wide, 6 inches tall
ax = fig.add_subplot(111)
ax.plot(x, y)
plt.show()
2. Modifying rcParams
for Global Changes
To change the default figure size for all plots, modify the rcParams
dictionary. This sets a default size unless overridden.
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
mpl.rcParams['figure.figsize'] = (8, 4) # Default: 8x4 inches
x = np.linspace(0, 10, 100)
y = np.cos(x)
plt.plot(x, y)
plt.show()
3. Using set_figheight()
and set_figwidth()
Adjust the size after figure creation using set_figheight()
and set_figwidth()
methods of the figure object.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.exp(-x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
fig.set_figheight(5) # 5 inches tall
fig.set_figwidth(12) # 12 inches wide
plt.show()
4. Using set_size_inches()
set_size_inches()
offers a concise way to change dimensions, taking a (width, height) tuple.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = x**2
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
fig.set_size_inches(7, 3) # 7x3 inches
plt.show()
5. Figure Formats and savefig()
The figure format (PNG, PDF, SVG) affects the saved output size. Higher-resolution formats (SVG) are scalable. Use savefig()
to control the format and resolution (dpi
).
import matplotlib.pyplot as plt
import numpy as np
# ... (Your plotting code) ...
plt.savefig("myplot.png", dpi=300) # High-resolution PNG
plt.savefig("myplot.pdf") # Vector format
plt.savefig("myplot.svg") # Vector format
These methods provide flexibility in managing Matplotlib plot sizes for clear and visually appealing visualizations.