How do I format axis number format to thousands with a comma in matplotlib?

后端 未结 7 1571
野性不改
野性不改 2020-11-29 20:48

How can I change the format of the numbers in the x-axis to be like 10,000 instead of 10000? Ideally, I would just like to do something like this:<

相关标签:
7条回答
  • 2020-11-29 21:19

    Short answer without importing matplotlib as mpl

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

    Modified from @AlexG's answer

    0 讨论(0)
  • 2020-11-29 21:21

    The best way I've found to do this is with StrMethodFormatter:

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

    For example:

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

    0 讨论(0)
  • 2020-11-29 21:23

    Use , as format specifier:

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

    Alternatively you can also use str.format instead of format:

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

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

    enter image description here

    0 讨论(0)
  • 2020-11-29 21:32

    If you like it hacky and short you can also just update the labels

    def update_xlabels(ax):
        xlabels = [format(label, ',.0f') for label in ax.get_xticks()]
        ax.set_xticklabels(xlabels)
    
    update_xlabels(ax)
    update_xlabels(ax2)
    
    0 讨论(0)
  • 2020-11-29 21:35

    You can use 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()
    

    enter image description here

    0 讨论(0)
  • 2020-11-29 21:39

    I always find myself on this same page everytime I try to do this. Sure, the other answers get the job done, but aren't easy to remember for next time! ex: import ticker and use lambda, custom def, etc.

    Here's a simple solution if you have an axes named ax:

    ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()])
    
    0 讨论(0)
提交回复
热议问题