【问题标题】:How do I format axis number format to thousands with a comma in matplotlib?如何在 matplotlib 中用逗号将轴数格式格式化为千位?
【发布时间】:2014-11-16 09:21:11
【问题描述】:

如何将 x 轴上的数字格式更改为 10,000 而不是 10000? 理想情况下,我只想做这样的事情:

x = format((10000.21, 22000.32, 10120.54), "#,###")

代码如下:

import matplotlib.pyplot as plt

# create figure instance
fig1 = plt.figure(1)
fig1.set_figheight(15)
fig1.set_figwidth(20)

ax = fig1.add_subplot(2,1,1)

x = 10000.21, 22000.32, 10120.54

y = 1, 4, 15
ax.plot(x, y)

ax2 = fig1.add_subplot(2,1,2)

x2 = 10434, 24444, 31234
y2 = 1, 4, 9
ax2.plot(x2, y2)

fig1.show()

【问题讨论】:

标签: python matplotlib


【解决方案1】:

如果您希望原始值出现在刻度中,请使用

plt.xticks(ticks=plt.xticks()[0], labels=plt.xticks()[0])

这将防止从 3000000 到 1.3 e5 等缩写,并以刻度显示 3000000(准确值)。

【讨论】:

    【解决方案2】:

    我认为最简单的方法:

    current_values = plt.gca().get_yticks()
    plt.gca().set_yticklabels(['{:,.0f}'.format(x) for x in current_values])
    

    来自: https://queirozf.com/entries/matplotlib-examples-number-formatting-for-axes-labels

    【讨论】:

      【解决方案3】:
      x = [10000.21, 22000.32, 10120.54]
      

      您可以使用列表推导来制作标签列表,然后将plt.xticks 传递给它们。

      xlabels = [f'{label:,}' for label in x]
      plt.xticks(x, xlabels)
      

      【讨论】:

      • 这对我有用,因为另一个问题是 StrMethodFormatter 无法解决的!谢谢
      【解决方案4】:

      不导入matplotlib as mpl的简答题

      plt.gca().yaxis.set_major_formatter(plt.matplotlib.ticker.StrMethodFormatter('{x:,.0f}'))
      

      根据@AlexG 的回答修改

      【讨论】:

        【解决方案5】:

        我发现最好的方法是使用StrMethodFormatter

        import matplotlib as mpl
        ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
        

        例如:

        import pandas as pd
        import requests
        import matplotlib.pyplot as plt
        import matplotlib as mpl
        
        url = 'https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USDT&aggregate=1'
        df = pd.DataFrame({'BTC/USD': [d['close'] for d in requests.get(url).json()['Data']]})
        
        ax = df.plot()
        ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
        plt.show()
        

        【讨论】:

        【解决方案6】:

        每次我尝试这样做时,我总是发现自己在同一个页面上。当然,其他答案可以完成工作,但下次不容易记住!例如:导入ticker并使用lambda、自定义def等。

        如果您有一个名为 ax 的坐标区,这是一个简单的解决方案:

        ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()])
        

        【讨论】:

        • 很好......单行,而且仍然相当可读。此外,易于修改,例如添加美元符号:...'${:,}'...
        • 我非常喜欢这个,效果很好。我必须把它放在我的范围设置器之后,ax.xaxis.set_major_locator(plt.MaxNLocator(20))
        【解决方案7】:

        如果你喜欢它的简洁和简短,你也可以只更新标签

        def update_xlabels(ax):
            xlabels = [format(label, ',.0f') for label in ax.get_xticks()]
            ax.set_xticklabels(xlabels)
        
        update_xlabels(ax)
        update_xlabels(ax2)
        

        【讨论】:

          【解决方案8】:

          你可以使用matplotlib.ticker.funcformatter

          import numpy as np
          import matplotlib.pyplot as plt
          import matplotlib.ticker as tkr
          
          
          def func(x, pos):  # formatter function takes tick label and tick position
              s = '%d' % x
              groups = []
              while s and s[-1].isdigit():
                  groups.append(s[-3:])
                  s = s[:-3]
              return s + ','.join(reversed(groups))
          
          y_format = tkr.FuncFormatter(func)  # make formatter
          
          x = np.linspace(0,10,501)
          y = 1000000*np.sin(x)
          ax = plt.subplot(111)
          ax.plot(x,y)
          ax.yaxis.set_major_formatter(y_format)  # set formatter to needed axis
          
          plt.show()
          

          【讨论】:

          • 改编自this答案。
          【解决方案9】:

          , 用作format specifier

          >>> format(10000.21, ',')
          '10,000.21'
          

          您也可以使用str.format 代替format

          >>> '{:,}'.format(10000.21)
          '10,000.21'
          

          matplotlib.ticker.FuncFormatter:

          ...
          ax.get_xaxis().set_major_formatter(
              matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
          ax2.get_xaxis().set_major_formatter(
              matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
          fig1.show()
          

          【讨论】:

          • 感谢 falsetru,在 matplot.ticker.FuncFormatter 上调整您的代码行成功了。
          • @IcemanBerlin,不客气。顺便说一句,我使用 int 删除小数。如果你想保留它,请删除int
          • 它很完美,我确实想排除小数,我可能不应该在示例中使用它们。我确实想知道是什么让他们失望了,所以再次感谢。
          猜你喜欢
          • 2022-12-21
          • 2022-12-06
          • 2017-08-23
          • 2020-07-30
          • 1970-01-01
          • 2015-04-13
          • 1970-01-01
          • 1970-01-01
          • 2013-06-01
          相关资源
          最近更新 更多