How can one remove, say, the first and last tick label of a plot if the plot is logarithmic?
Classic example:
import matplotlib.pyplot as plt
import numpy as np
ax1 = plt.subplot(1, 3, 1)
x = np.logspace(-3,1,100)
plt.plot(x,np.random.random(size=100))
plt.xscale('log')
ax2 = plt.subplot(1, 3, 2, sharey = ax1)
plt.plot(x,np.random.random(size=100))
plt.tick_params(axis='y',labelleft='off')
plt.subplots_adjust(wspace=0)
Leads to overlapping labels on the x axis.
Now if I do the most straightforward thing via *_ticklabels
, e.g.,
l = [""] + [i.get_text() for i in ax2.get_xticklabels()[1:-1]] + [""]
ax2.set_xticklabels(l)
it does not work (within a script that is, not if matplotlib draws the plot first).
One way I found around this is to use a custom ticker object. For example
from matplotlib.ticker import ScalarFormatter
class _MyTickFormatter(ScalarFormatter):
def __init__(self, hide):
self.hide = hide
super(self.__class__, self).__init__()
def __call__(self, x, pos=None):
N = len(self.locs)
hide = [ N + i if i < 0 else i for i in self.hide ]
if pos in hide:
return ''
else:
return self.pprint_val(x)
With this one can simply do ax2.set_major_formatter(_MyTickFormatter([0,-1]))
.
However, if the x-axis is, e.g., logarithmic (as above). Then the solution needs yet another custom tickformatter...
Another possibility is to use the MaxNLocator
as described in this answer by Bernie. However, using this in a logarithmic axes leaves me with only one tick (as it should use the LogLocator
, I assume).
Any ideas how I could solve this dilemma?