Back to Blog
Python

Matplotlib Figure Size, Titles, Labels, Legends, and Grids

Learn how to control Matplotlib figure size, titles, axis labels, legends, and grids in Python. Includes practical code examples and layout guidance.

MatplotlibData VisualizationPython PlottingFigure ConfigurationChart Styling
A Matplotlib chart with labeled axes, a legend, and a grid, showing the effect of figure size and layout settings.

Controlling a Matplotlib chart's figure size, titles, axis labels, legends, and grids is a common requirement, and the library provides explicit methods and parameters for each. The examples below show how to set these elements, how they interact, and how to avoid frequent 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 built-in 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, use a rounded box, or adjust the font size:

ax.legend(loc='upper right', frameon=True, fancybox=True, fontsize=10)

If you need to assign labels after plotting, pass them as a list to ax.legend(['Actual', 'Forecast']), but only when the plotted artists do not 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 stronger line for major ticks and a lighter dotted line for minor ticks. To enable minor ticks and their grid, call ax.minorticks_on() and then pass which='minor' to ax.grid():

ax.minorticks_on() ax.grid(True, which='major', linestyle='-', linewidth=0.8) ax.grid(True, which='minor', linestyle=':', linewidth=0.4)

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 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() can prevent 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 means the text occupies a smaller fraction of the figure. 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.

How to Set Matplotlib Figure Size, Titles, Labels, Legends, and Grids in Python | RYUSLOG DEV