I'm trying to format the yticks of a plot as pounds with a '£' and ideally a comma separator. Currently the yticks are represented like this: 20000, 30000, 40000. I'm aiming for this: £20,000, £30,000, £40,000, etc.
Here is an equivalent reproducible example:
import seaborn as sis
tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="tip", data=tips, whis=np.inf)
sns.stripplot(x="day", y="tip", data=tips, jitter=True)
How would I format these yticks like this: £12.00, £10.00, £8.00, etc.
After 3 hours of googling and failing with all sorts of plt.ytick
and ax.set_yticklabels
options I'm totally lost.
You can use StrMethodFormatter
, which uses the str.format()
specification mini-language.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import seaborn as sns
fig, ax = plt.subplots()
# The next line uses `utf-8` encoding. If you're using something else
# (say `ascii`, the default for Python 2), use
# `fmt = u'\N{pound sign}{x:,.2f}'`
# instead.
fmt = '£{x:,.2f}'
tick = mtick.StrMethodFormatter(fmt)
ax.yaxis.set_major_formatter(tick)
tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="tip", data=tips, whis=np.inf, ax=ax)
sns.stripplot(x="day", y="tip", data=tips, jitter=True, ax=ax)
The comma in fmt = '£{x:,.2f}'
turns on the thousands separator, so it'll also work as you want for higher amounts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With