35

Given the following bar chart:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'A': ['A', 'B'], 'B': [1000,2000]})

fig, ax = plt.subplots(1, 1, figsize=(2, 2))

df.plot(kind='bar', x='A', y='B',
        align='center', width=.5, edgecolor='none', 
        color='grey', ax=ax)
plt.xticks(rotation=25)
plt.show()

enter image description here

I'd like to display the y-tick labels as thousands of dollars like this:

$2,000

I know I can use this to add a dollar sign:

import matplotlib.ticker as mtick
fmt = '$%.0f'
tick = mtick.FormatStrFormatter(fmt)
ax.yaxis.set_major_formatter(tick)

...and this to add a comma:

ax.get_yaxis().set_major_formatter(
     mtick.FuncFormatter(lambda x, p: format(int(x), ',')))

...but how do I get both?

2 Answers 2

70

You can use StrMethodFormatter, which uses the str.format() specification mini-language.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick

df = pd.DataFrame({'A': ['A', 'B'], 'B': [1000,2000]})

fig, ax = plt.subplots(1, 1, figsize=(2, 2))
df.plot(kind='bar', x='A', y='B',
        align='center', width=.5, edgecolor='none', 
        color='grey', ax=ax)

fmt = '${x:,.0f}'
tick = mtick.StrMethodFormatter(fmt)
ax.yaxis.set_major_formatter(tick) 
plt.xticks(rotation=25)

plt.show()

Both commas and dollar signs

3
  • 10
    is there away to make it 1K,2K,.. instead? Commented Feb 21, 2018 at 5:14
  • 10
    Worth noting the annoyingly confusing method names: StrMethodFormatter and FormatStrFormatter Commented Oct 11, 2018 at 15:40
  • 1
    For adding thousands, you could do this: define a function: currency = lambda x, pos: "${x:,.0f}k".format(x * 1e-3) and pass the function in the formatter ax.yaxis.set_major_formatter(currency)
    – igorkf
    Commented Nov 30, 2022 at 20:07
4

You can also use the get_yticks() to get an array of the values displayed on the y-axis (0, 500, 1000, etc.) and the set_yticklabels() to set the formatted value.

df = pd.DataFrame({'A': ['A', 'B'], 'B': [1000,2000]})

fig, ax = plt.subplots(1, 1, figsize=(2, 2))

df.plot(kind='bar', x='A', y='B', align='center', width=.5, edgecolor='none', 
        color='grey', ax=ax)

--------------------Added code--------------------------
# getting the array of values of y-axis
ticks = ax.get_yticks()
# formatted the values into strings beginning with dollar sign
new_labels = [f'${int(amt)}' for amt in ticks]
# Set the new labels
ax.set_yticklabels(new_labels)
-------------------------------------------------------
plt.xticks(rotation=25)
plt.show()

Not the answer you're looking for? Browse other questions tagged or ask your own question.