pythonmatplotlibcurrency-formatting

Formatting negative currency


I want to plot negative currency amounts as labels. Here is some code that I found:

fmt = '${x:,.0f}'
tick = mtick.StrMethodFormatter(fmt)
axes.yaxis.set_major_formatter(tick)

This will show negative $45 as $-45 on the Y-axis. What is the correct format to display -$45 instead?

Note: This question was closed because the same question was asked before. However, if you check the answer to that earlier question, it does not work for negative currencies, leading to the exact problem discussed in my question below, which has an accepted answer. Indeed, the solution in the older question was to use fmt = '${x:,.0f}'.


Solution

  • You can define a custom tick function that formats the tick labels based on whether they are positive or negative, check this example:

    import matplotlib.pyplot as plt
    import matplotlib.ticker as mtick
    import numpy as np
    
    x = np.arange(5)
    y = np.array([-100, -50, 0, 50, 100])
    
    # custom tick function
    def currency_ticks(x, pos):
        if x >= 0:
            return '${:,.0f}'.format(x)
        else:
            return '-${:,.0f}'.format(abs(x))
    
    fig, ax = plt.subplots()
    
    ax.plot(x, y)
    
    # format the y-axis tick labels using custom func
    tick = mtick.FuncFormatter(currency_ticks)
    ax.yaxis.set_major_formatter(tick)
    
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_title('Title')
    
    plt.show()