【问题标题】:MatPlotLib Dollar Sign with Thousands Comma Tick LabelsMatPlotLib 美元符号与数千个逗号刻度标签
【发布时间】:2018-06-05 20:57:31
【问题描述】:

给定以下条形图:

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 标签显示为数千美元,如下所示:

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), ',')))

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

提前致谢!

【问题讨论】:

    标签: python-3.x matplotlib comma display dollar-sign


    【解决方案1】:

    您还可以使用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()
    
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 有没有办法让它变成 1K、2K、.. 代替?
      • 值得注意的是令人讨厌的令人困惑的方法名称:StrMethodFormatterFormatStrFormatter
      猜你喜欢
      • 2016-11-04
      • 2017-03-10
      • 2019-03-17
      • 2020-05-29
      • 2021-02-19
      • 2018-06-19
      • 2010-11-16
      • 1970-01-01
      相关资源
      最近更新 更多