Shahar
Shahar

Reputation: 896

minor ticklabel format of log scale

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)

image result

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')
)

second image result

any ideas on how to get finer control in such cases?

Upvotes: 3

Views: 302

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

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()

enter image description here

Upvotes: 2

Related Questions