0

In Matplotlib, a log-log plot generates unwanted y-axis tick labels for the minor ticks. I tried this code, which specifies the (major) y-axis ticks to be [1,1.2,1.4,1.6] and expecting that any y-axis minor ticks will have no labels.

# imports
import numpy as np
from matplotlib import pyplot as plt

# data
x = np.linspace(0,4,31)
y1 = 1.7 - 0.3*x
y1min = y1-0.05
y1max = y1+0.05

# ticks
yticks = [1,1.2,1.4,1.6]
yticklabels = [str(yt) for yt in yticks]

# figure
plt.figure()
plt.plot(x,y1,color='r')
plt.ylim([0.9,1.6])
plt.xlabel('x')
plt.xscale('log')
plt.yscale('log')
plt.ylabel('y')
plt.yticks(yticks)
plt.gca().set_yticklabels(minor='off',labels=yticklabels)
plt.show()

which produces the following plot.

code output

Surprisingly the minor y-axis ticks have the labels specified specified for the major ones (i.e. with incorrect values), while the major y-axis ticks have the correct values, but in scientific (exponential) notation instead of the desired normal notation.

How can I remove the minor tick labels on the y axis (hopefully without resorting to mticker), while keeping the x-axis minor tick labels, and have the major y-axis tick labels follow the values I specified with yticklabels?

gammarayon
  • 92
  • 3
  • 9
  • Shouldn't it be `set_yticklabels(minor=False,...)` instead of `set_yticklabels(minor='off',...)`? See https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_yticklabels.html – JohanC Nov 27 '22 at 12:26
  • Unfortunately, your suggestion (if I got it correctly) of `plt.gca().set_yticklabels(minor=False,labels=yticklabels)` gives labels on both major and minor y-axis ticks, this time with the correct labels on the major y-axis ticks, but alas with labels (in scientific notation) for the minor y-axis ticks. – gammarayon Nov 27 '22 at 19:47
  • Well, you ALSO need `plt.minorticks_off()`. – JohanC Nov 27 '22 at 21:40
  • OK, thanks, but I wish to keep the minor ticks (in fact on both axes), and just have them without labels for the y axis. – gammarayon Nov 28 '22 at 19:04
  • 1
    `plt.gca().tick_params(which='minor', labelleft=False)` – JohanC Nov 28 '22 at 19:12
  • Thanks JohanC! It worked indeed, with `ax = plt.gca()` `ax.tick_params(which='minor',labelleft=False)` `ax.set_xticklabels(labels=xticklabels)` `ax.set_yticklabels(labels=yticklabels)` – gammarayon Nov 28 '22 at 21:46

1 Answers1

0

To disable the minor ticks of a log plot in matplotlib, we can use minorticks_off() method.

  • 2nd reply after deleting first one: Yes, but I wish to disable the y-axis labels from the minor y-axis ticks. I thought that this would be done with `plt.gca().set_yticklabels(labels=yticklabels)` or with `plt.gca().set_yticklabels(minor='off',labels=yticklabels)`, but none of these suppress the unwanted labels on the y-axis minor ticks. – gammarayon Nov 28 '22 at 19:07