带有数千个逗号刻度标签的 MatPlotLib 美元符号

MatPlotLib Dollar Sign with Thousands Comma Tick Labels

给定以下条形图:

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

我想像这样将 y 刻度标签显示为数千美元:

2,000 美元

我知道我可以用它来添加美元符号:

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

...然后添加一个逗号:

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

...但是我如何同时获得两者?

提前致谢!

您可以使用 StrMethodFormatter,它使用 str.format() 规范迷你语言。

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

您还可以使用 get_yticks() 获取 y 轴上显示的值的数组(0、500、1000 等),并使用 set_yticklabels() 设置格式化值.

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