Matplotlib : duplicate tick sets of tick marks with loglog plot?

Question:

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.

Asked By: Donna

||

Answers:

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

Answered By: thmslmr
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.