0

I would like customized tick marks for a loglog plot in Matplotlib. But in some cases (although not all), the default tick marks chosen by the loglog plot are not overwritten by my custom tick marks. Instead, both sets of tick marks show up in the plot.

In the following, I use xticks to get custom tick marks and labels at [224, 448, 896, 1792]. The problem is that tick marks at 3 x 10^2, 4 x 10^2 and 6 x 10^2 also show up. These appear to be left over from the initial call to loglog and are not overwritten by my custom ticks.

Using the same approach to set custom y-ticks works as expected in the plot below, although I have seen the same strange behavior when setting y-ticks in other plots.

import matplotlib.pyplot as plt

P = [224, 448, 896, 1792]
T = [4200, 2300,1300, 1000]

plt.loglog(P,T,'.-',ms=10)

pstr =[f"{p:d}" for p in P]
plt.xticks(P,pstr);

ytick = [1000, 2000, 3000, 4000]
pstr =[f"{pt:d}" for pt in ytick]
plt.yticks(ytick,pstr);

plt.show()

Duplicate tick marks with loglog plot

I don't always see this behavior, but it shows up often enough to be annoying.

Is this a bug? Or is there something I am missing?

Edit This post provides an answer, but only if one realizes that the problem I had was due to minor tick marks. In any case, my question was promptly answered here.

Donna
  • 1,390
  • 1
  • 14
  • 30
  • 2
    Matplotlib uses both "major" and "minor" tick marks. By default, you only change the major ticks. You could add `plt.minorticks_off()` to remove the minor ticks. – JohanC Mar 05 '23 at 21:30
  • Perfect! I didn't think to consider minor tick marks. Thank you! – Donna Mar 05 '23 at 22:01

1 Answers1

1

This is because {x,y}scale("log") will generate minor tick labels that are displayed in addition to the major tick labels that you are creating.

Adding plt.minorticks_off() before plt.show() should help you generate the figure you want.

Another option is to reset the X and Y minor ticks

# [...]
pstr = [f"{p:d}" for p in P]
plt.xticks(P, pstr)
plt.xticks([], minor=True)  # Remove X minor ticks

ytick = [1000, 2000, 3000, 4000]
pstr =[f"{pt:d}" for pt in ytick]
plt.yticks(ytick, pstr)
plt.yticks([], minor=True)  # Remove Y minor ticks

# [...]

Both options should give you the following figure :

enter image description here

thmslmr
  • 1,251
  • 1
  • 5
  • 11