Format y axis as percent

I have an existing plot that was created with pandas like this:


The y axis is format as float and I want to change the y axis to percentages. All of the solutions I found use syntax and I can only place code below the line above that creates the plot (I cannot add ax=ax to the line above.)

How can I format the y axis as percentages without changing the line above?

Here is the solution I found but requires that I redefine the plot :

    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib.ticker as mtick

    data = [8,12,15,17,18,18.5]
    perc = np.linspace(0,100,len(data))

    fig = plt.figure(1, (7,4))
    ax = fig.add_subplot(1,1,1)

    ax.plot(perc, data)

    fmt = '%.0f%%' # Format you want the ticks, e.g. '40%'
    xticks = mtick.FormatStrFormatter(fmt)

Link to the above solution: Pyplot: using percentage on x axis

pandas dataframe plot will return the ax for you, And then you can start to manipulate the axes whatever you want.

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

enter image description here


Back to homepage or read more recommendations: