美元符号和千位逗号刻度标签

32

给定以下条形图:

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

我想将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), ',')))

...但是我怎么同时得到两个呢?

2个回答

69
你可以使用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()

逗号和美元符号


9
有办法将它变成1K、2K等吗? - weefwefwqg3
10
值得注意的是这些令人困惑的方法名称:StrMethodFormatterFormatStrFormatter - Boris Yakubchik
1
要添加数千,您可以这样做:定义一个函数:currency = lambda x, pos: "${x:,.0f}k".format(x * 1e-3),并将该函数传递给格式化程序ax.yaxis.set_major_formatter(currency) - igorkf

3
你可以使用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()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接