Format y axis as percent
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:
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:
Taking it a notch above
For advanced formatting or unique requirements that PercentFormatter
doesn't support, venture into the realm of FuncFormatter
:
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:
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:
A simple list comprehension and str.format
method gets you your custom labels.
Was this article helpful?