Matplotlib Figure Size, Titles, Labels, Legends, and Grids
python matplotlib figure size titles labels legends and grids: Learn to control figure size, titles, axis labels, legends, and grids in Python Matplotlib with clear co...
python matplotlib figure size titles labels legends and grids requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.
When you create a plot with Python's Matplotlib, the default figure size, titles, labels, legends, and grids rarely match the needs of a real report or dashboard. This article shows how to set each of these elements explicitly so your charts are readable and consistent. You'll learn the core methods and parameters, how they interact, and how to avoid common layout problems.
Setting the Figure Size
The figure size in Matplotlib is controlled by the figsize parameter, which is available in plt.figure() and plt.subplots(). It takes a tuple of (width, height) in inches. The default is (6.4, 4.8), which often produces plots that are too small for presentations or too wide for documents.
import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(8, 5)) ax.plot([1, 2, 3], [4, 5, 6]) plt.show()
Setting the figure size at creation is the most direct approach. If you need to change the size after the figure exists, use fig.set_size_inches():
fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 5, 6]) fig.set_size_inches(10, 6) plt.show()
Keep in mind that figsize only affects the overall canvas. The axes will scale to fill the figure, but the spacing between subplots or the margins may need adjustment when you change the size. For a single plot, figsize is usually enough.
Adding Titles and Axis Labels
Titles and axis labels are set through the Axes object. The set_title() method adds a title above the plot, and set_xlabel() and set_ylabel() label the axes.
fig, ax = plt.subplots(figsize=(8, 5)) ax.plot([1, 2, 3], [4, 5, 6]) ax.set_title('Quarterly Revenue') ax.set_xlabel('Month') ax.set_ylabel('Revenue ($)') plt.show()
You can also pass font properties directly to these methods. For example, to increase the title size and make it bold:
ax.set_title('Quarterly Revenue', fontsize=16, fontweight='bold')
If you're using the pyplot state-machine interface, the equivalent functions are plt.title(), plt.xlabel(), and plt.ylabel(). They operate on the current axes. Prefer the explicit ax methods when you have multiple subplots, because they make it clear which axes you're modifying.
Configuring Legends
Legends identify the data series in a plot. To create a legend, you need to provide labels for the plotted elements. The simplest way is to pass a label argument to each plotting call and then call ax.legend().
fig, ax = plt.subplots(figsize=(8, 5)) ax.plot([1, 2, 3], [4, 5, 6], label='Actual') ax.plot([1, 2, 3], [6, 5, 4], label='Forecast') ax.legend() plt.show()
The loc parameter controls where the legend appears. Common values are 'upper right', 'lower left', 'center', and 'best'. The 'best' option tries to place the legend where it overlaps the least data.
ax.legend(loc='upper left')
You can also customize the legend's appearance. For instance, to add a frame, change its opacity, or adjust the font size:
ax.legend(loc='upper right', frameon=True, fancybox=True, fontsize=10)
If you need to set labels after plotting, use the label parameter in the legend call itself, but only if the plotted artists don't already have labels. A cleaner approach is to always set label when plotting and call ax.legend() once.
Styling Grids
Grids help readers compare data points against the axes. By default, Matplotlib does not show a grid. You enable it with ax.grid(True) or ax.grid().
fig, ax = plt.subplots(figsize=(8, 5)) ax.plot([1, 2, 3], [4, 5, 6]) ax.grid(True) plt.show()
You can control which grid lines appear by passing axis='x' or axis='y'. For example, to show only vertical grid lines:
ax.grid(True, axis='x')
Grid styling goes beyond a simple on/off switch. The linestyle, linewidth, and color parameters let you match the grid to your chart's theme:
ax.grid(True, linestyle='--', linewidth=0.5, color='gray', alpha=0.7)
A common pattern is to use a subtle dashed grid for the major ticks and a lighter grid for minor ticks. To enable minor ticks and their grid, you need to set the minor locator first:
import matplotlib.ticker as ticker ax.grid(True, which='major', linestyle='-', linewidth=0.8) ax.grid(True, which='minor', linestyle=':', linewidth=0.4) ax.minorticks_on()
This gives you fine-grained control over the visual hierarchy of the grid.
Combining All Elements in a Complete Example
Here's a realistic example that brings together figure size, titles, labels, legends, and grids in a single plot:
import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(10, 6)) months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] sales = [120, 135, 140, 155, 160, 175] forecast = [125, 130, 145, 150, 165, 180] ax.plot(months, sales, marker='o', label='Actual Sales') ax.plot(months, forecast, marker='s', linestyle='--', label='Forecast') ax.set_title('Monthly Sales vs Forecast', fontsize=16, fontweight='bold') ax.set_xlabel('Month', fontsize=12) ax.set_ylabel('Units Sold', fontsize=12) ax.legend(loc='upper left', frameon=True, fancybox=True, shadow=True) ax.grid(True, linestyle='--', alpha=0.6) plt.show()
This example demonstrates how each element contributes to a clear, publication-ready chart. The figsize ensures the plot is wide enough for the labels and legend, the title and labels provide context, the legend distinguishes the two series, and the grid improves readability without overwhelming the data.
Managing These Settings Across Multiple Plots
When you create many plots with the same styling, repeating the same figsize, title, label, legend, and grid settings becomes tedious and error-prone. Two common solutions are helper functions and rcParams.
A helper function wraps the common configuration:
def style_ax(ax, title, xlabel, ylabel): ax.set_title(title, fontsize=14) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.grid(True, linestyle='--', alpha=0.6) return ax fig, ax = plt.subplots(figsize=(8, 5)) ax.plot([1, 2, 3], [4, 5, 6]) style_ax(ax, 'Revenue', 'Month', 'Amount') plt.show()
For global defaults, you can modify rcParams at the start of your script. This affects all subsequent figures:
import matplotlib as mpl mpl.rcParams['figure.figsize'] = (8, 5) mpl.rcParams['axes.grid'] = True mpl.rcParams['axes.grid.linestyle'] = '--' mpl.rcParams['axes.grid.alpha'] = 0.6 mpl.rcParams['legend.loc'] = 'upper left'
Be careful with rcParams because it changes the behavior of every plot in the session. If you need different styles for different plots, a helper function is safer.
Another consideration is layout. When you add a title, labels, and a legend, the plot area can become cramped. Using fig.tight_layout() or constrained_layout=True in subplots() prevents overlapping elements. For example:
fig, ax = plt.subplots(figsize=(8, 5), constrained_layout=True)
This adjusts the spacing automatically and is especially useful when you have multiple subplots. If you prefer manual control, fig.subplots_adjust() lets you set exact margins.
Finally, remember that the figure size interacts with text scaling. A larger figure with the same font size will have relatively smaller text. If you increase figsize, you may need to increase fontsize in titles, labels, and legends to keep the text readable. This is a common oversight when exporting plots for presentations or posters.