A simple yet essential question!
You can change the size of a plot in Matplotlib using the figsize parameter. To make your plot wider, you'll adjust the width component of figsize. Here's how:
Method 1: Using figsize in plt.figure()
Before creating your plot, set the figure size using:
import matplotlib.pyplot as plt
# Set figure size: width (inches) x height (inches)
plt.figure(figsize=(10, 6)) # Width: 10 inches, Height: 6 inches
# Now create your plot
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y)
plt.title('Example Plot')
plt.show()
In this example, figsize=(10, 6) sets the figure width to 10 inches and height to 6 inches. Adjust the first value (10) to make your plot wider or narrower.
Method 2: Using rcParams (global setting)
If you want to set the figure size for all plots in your script/notebook, use rcParams:
import matplotlib.pyplot as plt
# Set global figure size (width x height, in inches)
plt.rcParams['figure.figsize'] = (12, 8) # Wider plot: 12 inches
# Now create your plots as usual
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y)
plt.title('Example Plot')
plt.show()
Here, plt.rcParams['figure.figsize'] = (12, 8) sets the default figure size for all subsequent plots.
Method 3: Using set_size_inches() (for existing figures)
If you've already created a figure and want to resize it:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
ax.plot(x, y)
# Resize the existing figure
fig.set_size_inches(11, 7) # Width: 11 inches, Height: 7 inches
plt.title('Example Plot')
plt.show()
Tips:
- The unit of measurement for
figsize is inches. Yes, inches! Not pixels.
- When saving plots to file (e.g.,
plt.savefig('plot.png')), the figsize setting is respected. The resulting image will have the specified size (in inches) at the set DPI (dots per inch, default is 100).
- If you're working in a Jupyter Notebook, you might need to rerun the cell after adjusting
figsize or rcParams for changes to take effect.
- Common width values:
- Small:
(6, 4)
- Medium:
(8, 6) (default)
- Large:
(10, 7) or (12, 8)
- Extra-wide:
(14, 7) or (16, 6)
Now, go ahead and widen those plots!