Reputation: 896
Trying to control the minor ticklabels in the following example:
fig, ax = plt.subplots(figsize=(6, 1.5))
ax.set_yscale('log')
ax.set_ylim(0.3, 2)
ax.yaxis.set_minor_formatter(
plt.LogFormatter(minor_thresholds=(1, 0.5))
)
ax.yaxis.set_major_formatter(
plt.FormatStrFormatter('%.0f')
)
ax.tick_params('y', which='minor', labelsize=8)
The minor ticklables are correctly positioned but I want to get rid of the scientific notation and keep 0.3, 0.4, 0.6.
If I set the minor_formatter
to plt.FormatStrFormatter('%.1f')
for instance, I get overcrowding of the ticklabels:
ax.yaxis.set_minor_formatter(
plt.FormatStrFormatter('%.1f')
)
any ideas on how to get finer control in such cases?
Upvotes: 3
Views: 302
Reputation: 339775
Using a FuncFormatter
will give you full control over the labels. One can hence check if any given coordinate is in a list, and tick only those.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter, FuncFormatter
fig, ax = plt.subplots(figsize=(6, 1.5))
ax.set_yscale('log')
ax.set_ylim(0.3, 2)
def func(x, pos):
ticks = [0.3, 0.4, 0.6, 2]
if np.any(np.isclose(np.ones_like(ticks)*x, ticks)):
return f"{x:g}"
else:
return ""
ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
ax.yaxis.set_minor_formatter(FuncFormatter(func))
ax.tick_params('y', which='minor', labelsize=8)
plt.show()
Upvotes: 2