MatPlotLib美元符号与数千个逗号刻度标签 [英] MatPlotLib Dollar Sign with Thousands Comma Tick Labels

查看:133
本文介绍了MatPlotLib美元符号与数千个逗号刻度标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下条形图:

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-tick标签:

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?

提前谢谢!

推荐答案

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

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

这篇关于MatPlotLib美元符号与数千个逗号刻度标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆