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

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

提交回复
热议问题