Use Matplotlib set_yticklabels for Custom Y-Axis Labels in Python

When I first started visualizing data with Matplotlib over a decade ago, customizing tick labels on the y-axis was always a bit tricky. In this article, I’ll share practical ways to use set_yticklabels in Matplotlib to customize your y-axis labels effectively.

You’ll learn multiple methods to tweak labels, making your data visualization clearer and more appealing, especially if you’re working with data relevant like sales figures, population stats, or election results.

Let’s get in!

What is set_yticklabels in Matplotlib?

set_yticklabels is a method in Matplotlib that allows you to set custom labels on the y-axis ticks of your plot. By default, Matplotlib generates numeric labels based on the data range, but sometimes the default labels don’t communicate the story clearly.

For example, if you have a bar chart showing quarterly sales in dollars, you might want to format the y-axis labels as currency or add units like “K” for thousands. That’s where set_yticklabels comes in handy.

Read Module ‘matplotlib’ has no attribute ‘plot’

Basic Usage of set_yticklabels

Let me start with a simple example. Suppose you have a simple bar chart showing sales for four US regions:

import matplotlib.pyplot as plt

regions = ['Northeast', 'Midwest', 'South', 'West']
sales = [25000, 30000, 22000, 27000]

fig, ax = plt.subplots()
ax.bar(regions, sales)

# Set custom y-axis labels
ax.set_yticks([0, 10000, 20000, 30000, 40000])
ax.set_yticklabels(['$0', '$10K', '$20K', '$30K', '$40K'])

plt.show()

You can refer to the screenshot below to see the output.

set_yticklabels

Here, I first set the positions of the y-ticks using set_yticks(). Then, I replaced the default numeric labels with formatted strings that display dollar amounts in thousands. This makes the chart easier to read for anyone familiar with US currency.

Check out Module ‘matplotlib’ has no attribute ‘artist’

Method 1: Format Y-Tick Labels with Currency Symbols

In many US-based datasets, financial figures are common. You can format y-axis labels to show dollar signs and abbreviate large numbers.

import matplotlib.ticker as ticker

fig, ax = plt.subplots()
ax.bar(regions, sales)

# Use FuncFormatter to format y-ticks as currency
def currency_format(x, pos):
    if x >= 1000:
        return f'${int(x/1000)}K'
    else:
        return f'${int(x)}'
ax.yaxis.set_major_formatter(ticker.FuncFormatter(currency_format))

plt.show()

You can refer to the screenshot below to see the output.

ax.set_yticklabels

I find this method useful because it automatically formats labels based on the tick values, so you don’t have to manually specify each label. This is especially handy when your data range changes dynamically.

Method 2: Rotate Y-Tick Labels for Better Readability

Sometimes y-axis labels can overlap or become hard to read, especially if they are long or if you have many ticks.

fig, ax = plt.subplots()
ax.bar(regions, sales)

ax.set_yticks([0, 10000, 20000, 30000, 40000])
ax.set_yticklabels(['$0', '$10K', '$20K', '$30K', '$40K'], rotation=45)

plt.show()

You can refer to the screenshot below to see the output.

set_yticks

Rotating the y-tick labels by 45 degrees can improve readability. This is something I often do when plotting data like US state population figures or election vote counts, where numbers might be long or crowded.

Method 3: Change the Color and Font Size of Y-Tick Labels

To emphasize certain parts of your chart or to match your company’s branding, you might want to customize the color or font size of the y-axis labels.

fig, ax = plt.subplots()
ax.bar(regions, sales)

ax.set_yticks([0, 10000, 20000, 30000, 40000])
labels = ax.set_yticklabels(['$0', '$10K', '$20K', '$30K', '$40K'])

# Customize label properties
for label in labels:
    label.set_color('green')
    label.set_fontsize(12)

plt.show()

This method adds a touch of professionalism to your plots. I’ve used it in presentations where I needed to highlight financial growth or decline in specific US markets.

Read Matplotlib Time Series Plot

Method 4: Use Minor Ticks and Custom Labels

Matplotlib also allows you to set minor ticks and their labels, which can be useful for detailed charts.

fig, ax = plt.subplots()
ax.bar(regions, sales)

ax.set_yticks([0, 10000, 20000, 30000, 40000])
ax.set_yticklabels(['$0', '$10K', '$20K', '$30K', '$40K'])

# Set minor ticks
ax.yaxis.set_minor_locator(ticker.MultipleLocator(5000))
ax.yaxis.set_minor_formatter(ticker.FuncFormatter(lambda x, pos: f'${int(x/1000)}.5K' if x % 10000 != 0 else ''))

plt.show()

Minor ticks can provide additional granularity without cluttering the main labels. This is helpful for detailed financial reports or demographic breakdowns in the US Census data.

Things to Keep in Mind

  • When you use set_yticklabels, make sure the number of labels matches the number of ticks; otherwise, Matplotlib will raise a warning.
  • If you want your labels to update dynamically with zooming or panning, consider using formatters like FuncFormatter instead of static labels.
  • Customizing tick labels can sometimes interfere with default gridlines or tick marks, so always double-check your plot’s readability.

With these methods, you can take full control of your y-axis labels in Matplotlib, making your data visualizations both functional and visually appealing. Whether you’re analyzing US sales data, voter turnout, or regional demographics, mastering set_yticklabels will elevate your Python plotting skills.

Other Matplotlib articles you may like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.