Format y axis as percent

Format y axis as percent

Asked on December 24, 2018 in Pandas.
Add Comment


  • 3 Answer(s)

    The axis can be manipulated when the dataframe returns the ax.

    import pandas as pd
    import numpy as np
     
    df = pd.DataFrame(np.random.randn(100,5))
     
    # you get ax from here
    ax = df.plot()
    type(ax) # matplotlib.axes._subplots.AxesSubplot
     
    # manipulate
    vals = ax.get_yticks()
    ax.set_yticklabels(['{:,.2%}'.format(x) for x in vals])
    
    Answered on December 24, 2018.
    Add Comment

    The function FuncFormatter can be used since it is simple and dependent:

    import pandas as pd
    import numpy as np
    from matplotlib.ticker import FuncFormatter
     
    df = pd.DataFrame(np.random.randn(100,5))
     
    ax = df.plot()
    ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: '{:.0%}'.format(y)))
    
    Answered on December 24, 2018.
    Add Comment

    Refer here. before proceeding:

    When you import the function matplotlib.ticker it also needs to be formatted using PercentFormatter:

    import ...
    import matplotlib.ticker as mtick
     
    ax = df['myvar'].plot(kind='bar')
    ax.yaxis.set_major_formatter(mtick.PercentFormatter())
    

    The parameters max, decimals, symbol are for the function  PercentFormatter(). The max can be used to set value upto 100%.For example PercentFormatter(1.0). To set the number of digits after the decimal point the other two functions can be used.The defaults are None and %.The function decimals=None sets the number of digits after the decimal point.

    Answered on December 24, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.