I was looking to format the ticks in my y-axis (this thread Format y axis as percent is great) but a lot of the solutions were causing an AttributeError for my particular code
#Example code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# arbitary data to plot
df = pd.DataFrame(np.random.randn(100,2))
#plotting the data and then plotting a 0 line over the top
ax = df.plot()
ax = plt.plot([0,100],[0,0])
vals = ax.get_yticks()
ax.set_yticklabels(['{:,.2%}'.format(x) for x in vals])
plt.show()
A bit of testing revealed that the second plot call messed up the ax object it went from being: class 'matplotlib.axes._subplots.AxesSubplot' to class 'list'. Thus it was easy to work-around, don't attribute the second plot to ax:
ax = df.plot()
plt.plot([0,100],[0,0])
Or move the formatting line up in the code before the ax object gets changed:
ax = df.plot()
vals = ax.get_yticks()
ax.set_yticklabels(['{:,.2%}'.format(x) for x in vals])
ax = plt.plot([0,100],[0,0])
So my question is: What is the best practice? Both the work-around's feel incorrect, what is the best way to assign the plt.plot() call to ax object without changing it? Or would best practice be to use plt.plot(df.index, df) instead of df.plot()?
*Note dp8's answer in Format y axis as percent "plt.gca().set_yticklabels(['{:.0f}%'.format(x*100) for x in plt.gca().get_yticks()])" worked regardless of the mess that I made with calls to ax