MatPlotLib Dollar Sign with Thousands Comma Tick Labels

Solution 1:

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

Solution 2:

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()