Puzzling behavior for matplotlib.pyplot yticks([])

Viewed 71

I want to suppress pyplot's automatically generated tick labels in favor of my own labels. When I suppress the y-tick labels using pyplot.yticks([]) in the following Python script,

from matplotlib import pyplot as plt

num_points = 10
data       = [i for i in range(num_points)]
fig        = plt.figure()
ax         = plt.subplot(1,1,1)

ax.plot(data)
ax.set_yscale('log')
plt.yticks([])
plt.text(1, 7, '10 data points')

plt.show()

pyplot suppresses y-tick labels, as desired:

10 points log

But when the num_points is less than ten, pyplot ignores pyplot.yticks([]), inserts its automatically generated tick labels, and produces

9 points log

When I supply my own tick labels by supplying a list of value and a list of labels, via plt.yticks(values_list, labels_list), pyplot.yticks() accepts my labels, but it still draws its automatically generated tick labels, overwriting my labels.

If I change the nine-point log plot to a linear plot by omitting the ax.set_yscale('log') statement, pyplot does not draw automatically generate tick labels:

9 points linear

The problem appears to be related to log plots with fewer than ten points. How do I suppress the automatically generated tick labels in log plots having fewer than ten points?

1 Answers

When working with a log axis, not only the major ticks but also the minor ticks are shown by default. You can turn them off separately. Note that when there are only very few major ticks, the minor ticks also can get a label.

Also note it usually isn't a good idea to have zero values on a log scale. As log(0) is minus infinity, matplotlib has to do some fragile guesswork about the desired tick distances.

from matplotlib import pyplot as plt
from matplotlib import ticker

num_points = 10
data       = [i+2 for i in range(num_points)]
fig        = plt.figure()
ax         = plt.subplot(1,1,1)

ax.plot(data)
ax.set_yscale('log')
ax.text(1, 7, '10 data points')
ax.yaxis.set_major_locator(ticker.NullLocator())
ax.yaxis.set_minor_locator(ticker.NullLocator())

plt.show()

The image shows the major ticks in blue and the minor ticks in red. As in this example there is only one major tick, some of the minor ticks also got a label. enter image description here

Related