4

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:
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 Line plot with  default labels still there

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
hansf
  • 43
  • 4

2 Answers2

3

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

enter image description here

There are of course more sophisticated ways to handle ticks and labels, see e.g. this question for a similar issue.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
0

For me, to remove the default label I set the major labels to empty but not minor ones.

ax.set_xticklabels("",major=True)
ahmadi
  • 17
  • 7