1

I am trying to change the tick labels of a log-plot in matplotlib, which often works fine by setting the labels manually. However, often the problem shown below occurs, manually moving the labels seems to keep some of the old labels. Any idea how to fix this?

import matplotlib.pyplot as plt
%matplotlib inline

fig, ax = plt.subplots()
x = [1, 10]
y = [0, 1]
ax.plot(x, y)
ax.set_xscale('log')
ax.set_xlim(0, 10)

ax.set_xticks([2.5, 7.5])

Also, I recently upgraded to matplotlib 2.0.2 and I cannot remember having seen this behaviour before.

enter image description here

vestland
  • 55,229
  • 37
  • 187
  • 305
physicsGuy
  • 3,437
  • 3
  • 27
  • 35

1 Answers1

5

The values shown are the minor ticks, to disable them, you can state:

ax.minorticks_off()

This will result in the tick label for 7.5 dissapearing as well.

What you probably want, is the following solution:

from matplotlib.ticker import StrMethodFormatter, NullFormatter
ax.xaxis.set_major_formatter(StrMethodFormatter('{x:.1f}'))
ax.xaxis.set_minor_formatter(NullFormatter())
Uvar
  • 3,372
  • 12
  • 25
  • Thanks, that works! A short follow up question - How would you display the tick labels as 10^{-1}, 10^{-2} and if possible also 2 \times 10^{-1}. [Imagine it as LaTeX, I don't know how to display it on stackoverflow.] – physicsGuy Aug 14 '17 at 10:30
  • `ax.xaxis.set_major_formatter(StrMethodFormatter('{x:.0E}'))` after ofc setting the appropriate xticks; in the answer method, you force the format to 1 decimal place floating point; this would force it to 0 decimal scientific notation. There are ofc other options, but I am sure you can find topics on string formatting which can give you more info in a shorter amount of time than I can. ;) – Uvar Aug 14 '17 at 10:35
  • I was looking for something slightly different. Basically I wanted a formatter that displays the tick-labels with an actual exponent, as shown in my question. I found `matplotlib.ticker.LogFormatterMathtext` to do exactly that. Still, thanks for pointing me to the ticker subpackage, that was very helpful. – physicsGuy Aug 14 '17 at 12:05
  • Ah, whoops. My bad for misinterpreting, but still happy that you were able to find what you were looking for. – Uvar Aug 14 '17 at 12:13