Explain Codes LogoExplain Codes Logo

Format y axis as percent

python
matplotlib
plotting
data-visualization
Anton ShumikhinbyAnton Shumikhin·Feb 7, 2025
TLDR

To format a y-axis as percentages, employ PercentFormatter from matplotlib.ticker. You would generally apply this formatter after plotting your data. Here's a neat little snapshot of how this works:

# Import 'plot of gold' and 'magic formatter' import matplotlib.pyplot as plt from matplotlib.ticker import PercentFormatter # The 'precious' data data = [0.1, 0.6, 0.3, 1.0] # Example data as proportions # 'Unleash' the plot plt.plot(data) # Now, the 'magic trick' to format y-axis as percent plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) # Show the world the 'masterpiece' plt.show()

The above code will transform your y-axis to a percentage scale, ranging from 0% to 100%.

The art of customization

Now, the PercentFormatter is not just a tool, but an artist's palette. It provides options to alter elements such as:

  • xmax Parameter: Adjust this to define what value matches 100% on the y-axis.
  • Decimal Points: Determine the number of decimal places in the display.
  • symbol Parameter: Modify or completely remove the percent symbol.

Sample code highlighting these features:

# 'Fancy' customization plt.gca().yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=2, symbol='%'))

Taking it a notch above

For advanced formatting or unique requirements that PercentFormatter doesn't support, venture into the realm of FuncFormatter:

# Going 'ninja mode' from matplotlib.ticker import FuncFormatter # Our 'magic spell' fmt = lambda x, _: "{:.1f}%".format(x*100) # Unleashing the 'beast' plt.gca().yaxis.set_major_formatter(FuncFormatter(fmt))

Use Python 3.6+ f-strings for brevity or str.format for compatibility with older Python versions. Apply these formatters after plot creation to avoid messing up the base plot.

Pandas? No problem!

Even with pandas, you can whip up a perfectly formatted y-axis either by chaining methods or accessing the Axes object:

# 'Panda' at work ax = df.plot(kind='line') ax.yaxis.set_major_formatter(PercentFormatter(1))

In the above snippet, df is the DataFrame and line represents your plot kind. The PercentFormatter can then be chained directly to ax.

The tightrope walk

Traps you might fall into while grappling with formatting:

  • Data Constraints: Your data should ideally be between 0.0 and 1.0 while using PercentFormatter directly.
  • Duplicated Code: Overwriting axis ticks and labels post applying PercentFormatter creates unnecessary redundancy.
  • Contradictory Units: Be cautious while mixing percentage-formatted axes with non-percentage data. It can lead to misleading visuals.

Python's helping hand

Python's robust string formatting capabilities can spruce up your label styling. Use the following example to get manually set y-tick labels:

# 'Charmed' labels ax.set_yticklabels(['{:.0%}'.format(y) for y in ax.get_yticks()])

A simple list comprehension and str.format method gets you your custom labels.