Dollar Sign with Thousands Comma Tick Labels
Asked Answered
A

2

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?

Ascription answered 1/7, 2016 at 19:1 Comment(0)
K
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

Kelliekellina answered 1/7, 2016 at 19:10 Comment(3)
is there away to make it 1K,2K,.. instead?Kumkumagai
Worth noting the annoyingly confusing method names: StrMethodFormatter and FormatStrFormatterPapyrology
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) Celiaceliac
E
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()

Eccles answered 14/12, 2021 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.