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

后端 未结 7 1605
野性不改
野性不改 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: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()
    

提交回复
热议问题