Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seaborn and Pandas: How to set yticks formatted as UK pounds

Tags:

pandas

seaborn

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.

enter image description here

like image 331
RDJ Avatar asked Jan 05 '23 18:01

RDJ


1 Answers

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)

y-labels in pounds

The comma in fmt = '£{x:,.2f}' turns on the thousands separator, so it'll also work as you want for higher amounts.

like image 142
A. Garcia-Raboso Avatar answered Feb 24 '23 14:02

A. Garcia-Raboso