Pandas creates default yticklabels for logy plots. I want to replace these labels with my own labels but for some reason I can't seem to remove the default labels.
If I specify the yticks inside the plot
method, it just writes over the existing default label:
x = [1, 1.5, 2, 2.5, 3]
df = pd.DataFrame({'x': x})
ax = df.plot(logy=True, yticks=[2])
Line plot with overwritten labels:
Trying to remove the yticklabels by referencing the axes
directly doesn't help either:
ax = df.plot(logy=True)
ax.set_yticklabels([])
Line plot with default labels still there
Matplotlib plots may have major and minor ticks and ticklabels. In cases where the logarithmic plot ranges over less than a decade, minor ticklabels are set on by default. You may set them to an empty list, via ax.set_yticklabels([],minor=True)
, or you may turn them off completely via ax.minorticks_off()
.
Then you can set your custom ticks/-labels to whatever you like.
import pandas as pd
import matplotlib.pyplot as plt
x = [1, 1.5, 2, 2.5, 3]
df = pd.DataFrame({'x': x})
ax = df.plot(logy=True)
# turn minor ticklabels off
ax.set_yticklabels([],minor=True)
# or use
# ax.minorticks_off()
# set new custom ticks/-labels
ax.set_yticks([1,2,2.5])
ax.set_yticklabels(list("ABC"))
plt.show()
There are of course more sophisticated ways to handle ticks and labels, see e.g. this question for a similar issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With