0Pricing
Pandas & NumPy Academy · Lesson

Labels, Titles, and Saving Figures

Add axis labels, a title, a legend, and tick formatting, then save publication-quality figures with savefig().

Labels, Titles, and Saving Figures is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

From Plot to Publication

A chart is only effective if its axes are labelled, its title explains the takeaway, and it is saved at high enough resolution for its intended medium. This lesson covers the finishing touches that transform a quick exploratory plot into a polished figure suitable for a report, dashboard, or academic publication: axis labels, tick formatting, titles, legends, annotations, and file export.

Axis Labels with set_xlabel and set_ylabel

Set descriptive axis labels with ax.set_xlabel() and ax.set_ylabel(). Always include units in the label (e.g., 'Revenue (USD)' rather than just 'Revenue'). Use fontsize to make labels larger for presentations, and labelpad to add space between the axis and the label text when ticks are large.

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(7, 4))
x = np.arange(1, 13)
y = np.random.randint(100, 500, 12)
ax.plot(x, y, 'o-', color='steelblue')

ax.set_xlabel('Month', fontsize=12, labelpad=8)
ax.set_ylabel('Revenue (USD thousands)', fontsize=12, labelpad=8)
# plt.show()
plt.close()

Titles with set_title and suptitle

ax.set_title() sets the title above a single Axes. For multi-panel figures, fig.suptitle() adds a shared title above all subplots. Control font size with fontsize and vertical position with y (default 1.0). A good title states the main insight of the chart, not just what the axes are — compare 'Monthly Revenue' to 'Revenue Peaked in Q3 and Fell 20% in Q4'.

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.plot([1,2,3], [1,4,9])
ax1.set_title('Subplot One', fontsize=11)

ax2.bar(['A','B','C'], [3,7,2])
ax2.set_title('Subplot Two', fontsize=11)

# Shared figure title
fig.suptitle('Annual Overview Dashboard', fontsize=14, fontweight='bold', y=1.02)
plt.tight_layout()
plt.close()

Controlling Tick Labels

Matplotlib's default tick labels are often adequate, but sometimes you need custom labels. Use ax.set_xticks() to specify tick positions and ax.set_xticklabels() to set the labels. Pass rotation=45 to tilt long labels so they do not overlap. The ha='right' (horizontal alignment) parameter ensures rotated labels anchor correctly to their tick mark.

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
values = np.random.randint(200, 600, 12)

fig, ax = plt.subplots(figsize=(9, 4))
ax.bar(range(12), values, color='steelblue')
ax.set_xticks(range(12))
ax.set_xticklabels(months, rotation=45, ha='right', fontsize=10)
ax.set_ylabel('Revenue')
plt.tight_layout()
plt.close()

Formatting Tick Values

Use matplotlib.ticker formatters to display tick values in a human-readable format. FuncFormatter takes a function that receives the tick value and returns a formatted string. Common patterns: thousands separator, currency symbol, percentage sign, scientific notation. Apply with ax.yaxis.set_major_formatter(formatter).

from matplotlib.ticker import FuncFormatter

def millions_fmt(x, pos):
    return f'${x/1e6:.1f}M'

fig, ax = plt.subplots(figsize=(7, 4))
ax.bar(['Q1', 'Q2', 'Q3', 'Q4'], [1.2e6, 1.8e6, 2.1e6, 1.9e6], color='steelblue')
ax.yaxis.set_major_formatter(FuncFormatter(millions_fmt))
ax.set_title('Quarterly Revenue')
ax.set_ylabel('Revenue')
plt.tight_layout()
plt.close()

Legends with ax.legend()

Call ax.legend() to display a legend for all plot elements that have a label parameter set. Customise with loc (position, e.g., 'upper right', 'lower left'), ncol (number of columns), framealpha (box transparency), and fontsize. Placing the legend outside the plot area uses bbox_to_anchor combined with loc.

fig, ax = plt.subplots(figsize=(7, 4))
for region, color in [('East','steelblue'),('West','coral'),('North','green')]:
    ax.plot(range(12), np.random.randint(100, 400, 12),
            marker='o', label=region, color=color)

ax.legend(loc='upper right', ncol=1, framealpha=0.8, fontsize=10)
ax.set_title('Monthly Sales by Region')
plt.close()

Adding Text Annotations

ax.annotate(text, xy=(x_point, y_point), xytext=(x_text, y_text), arrowprops=...) adds a text label with an optional arrow pointing to a specific data point. Use this to highlight maximum values, anomalies, or important events on a chart. The arrowprops dict controls the arrow style: arrowstyle='->' is a simple arrow.

y_vals = np.array([120, 180, 310, 250, 420, 380, 290])
x_vals = np.arange(len(y_vals))
peak_idx = np.argmax(y_vals)

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x_vals, y_vals, 'o-', color='steelblue')
ax.annotate(f'Peak: {y_vals[peak_idx]}',
            xy=(peak_idx, y_vals[peak_idx]),
            xytext=(peak_idx - 2, y_vals[peak_idx] + 30),
            arrowprops={'arrowstyle': '->', 'color': 'red'},
            fontsize=10, color='red')
plt.close()

Adding Horizontal and Vertical Reference Lines

ax.axhline(y_value) draws a horizontal line across the full width of the Axes at the specified y-value. ax.axvline(x_value) draws a vertical line. Both accept color, linestyle, and linewidth parameters. Reference lines are commonly used to mark targets, thresholds, or event dates on time series charts.

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(range(10), np.random.randint(100, 400, 10), 'o-', color='steelblue')

# Target line
ax.axhline(y=250, color='red', linestyle='--', lw=1.5, label='Target')

# Event line
ax.axvline(x=5, color='orange', linestyle=':', lw=1.5, label='Campaign start')

ax.legend()
ax.set_title('Revenue vs Target')
plt.close()

Styling with Themes

Matplotlib includes several built-in style sheets that change the overall look of all figures without code changes: 'seaborn-v0_8-whitegrid', 'fivethirtyeight', 'ggplot', 'bmh', etc. Apply a style with plt.style.use('style_name') at the start of your script. Use plt.style.context('style_name') as a context manager to apply a style only within a block.

# Apply a style globally
plt.style.use('seaborn-v0_8-whitegrid')
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(range(10), np.random.randn(10).cumsum())
ax.set_title('Seaborn Whitegrid Style')
plt.close()

# Reset to default
plt.rcdefaults()

Saving Figures with savefig()

fig.savefig('filename.png') saves the figure to a file. Key parameters: dpi (dots per inch — use 150 for screen, 300 for print), bbox_inches='tight' (prevents labels from being clipped), and format (inferred from the extension or specified explicitly). Common formats: '.png' (raster, good for web), '.pdf' (vector, good for print), '.svg' (vector, editable in Illustrator).

fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(range(10), np.random.randn(10), 'o-')
ax.set_title('Export Example')
ax.set_xlabel('Step')
ax.set_ylabel('Value')

# Save as PNG (screen quality)
fig.savefig('/tmp/chart_screen.png', dpi=150, bbox_inches='tight')

# Save as PDF (print quality)
fig.savefig('/tmp/chart_print.pdf', dpi=300, bbox_inches='tight')

plt.close()
print('Figures saved.')

Complete Example: Polished Report Chart

Here is a complete workflow combining all the techniques in this lesson: a polished time series chart with axis labels, formatted y-axis ticks, a horizontal target line, an annotation on the peak, and export to a high-resolution PNG. This is the pattern you will use for any chart that goes into a report or dashboard.

from matplotlib.ticker import FuncFormatter

fig, ax = plt.subplots(figsize=(9, 5))
months = list(range(1, 13))
revenue = [120, 145, 132, 160, 175, 190, 210, 185, 220, 200, 240, 260]
peak = max(revenue)
peak_idx = revenue.index(peak)

ax.plot(months, revenue, 'o-', color='steelblue', lw=2, markersize=6)
ax.axhline(y=180, color='red', ls='--', lw=1.2, label='Target: $180K')
ax.annotate(f'Peak ${peak}K', xy=(peak_idx+1, peak),
            xytext=(peak_idx-1.5, peak+15),
            arrowprops={'arrowstyle': '->'}, fontsize=9)
ax.set_xticks(months)
ax.set_xticklabels(['Jan','Feb','Mar','Apr','May','Jun',
                    'Jul','Aug','Sep','Oct','Nov','Dec'], rotation=45, ha='right')
ax.yaxis.set_major_formatter(FuncFormatter(lambda x,p: f'${x:.0f}K'))
ax.set_title('2024 Monthly Revenue vs Target', fontsize=13, fontweight='bold')
ax.set_ylabel('Revenue')
ax.legend()
plt.tight_layout()
plt.close()

Quick Check

Test your understanding of labels, titles, and saving figures from this lesson.

Lesson Recap

In this lesson you learned: set_xlabel()/set_ylabel()/set_title() add descriptive text; FuncFormatter formats tick values as currency or percentages; ax.annotate() adds pointed text labels to highlight key data points; axhline()/axvline() draw reference lines; and fig.savefig() with dpi and bbox_inches='tight' produces publication-quality exports. This completes the Matplotlib Fundamentals course — next up is Seaborn for statistical plots.

Frequently asked questions

Is the “Labels, Titles, and Saving Figures” lesson free?

Yes — the full text of “Labels, Titles, and Saving Figures” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.

What will I learn in “Labels, Titles, and Saving Figures”?

Add axis labels, a title, a legend, and tick formatting, then save publication-quality figures with savefig(). You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Pandas & NumPy Academy?

No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Labels, Titles, and Saving Figures” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Pandas & NumPy Academy lesson?

Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Figure and Axes Architecture
  2. Line and Scatter Plots
  3. Bar Charts and Histograms
  4. Labels, Titles, and Saving Figures
← Back to Pandas & NumPy Academy