对数刻度的次要刻度标签格式

时间:2019-08-19 16:12:49

标签: python matplotlib

在以下示例中尝试控制次要刻度标签:

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

次要滴答声的位置正确,但我想摆脱科学记数法,并保持0.3、0.4、0.6。

例如,如果我将minor_formatter设置为plt.FormatStrFormatter('%.1f'),我会出现刻度标签拥挤的情况:

ax.yaxis.set_minor_formatter(
    plt.FormatStrFormatter('%.1f')
)

second image result

在这种情况下如何获得更好的控制的任何想法?

1 个答案:

答案 0 :(得分:1)

使用FuncFormatter将使您完全控制标签。因此,可以检查列表中是否有给定的坐标,并仅勾选那些坐标。

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