在以下示例中尝试控制次要刻度标签:
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)
次要滴答声的位置正确,但我想摆脱科学记数法,并保持0.3、0.4、0.6。
例如,如果我将minor_formatter
设置为plt.FormatStrFormatter('%.1f')
,我会出现刻度标签拥挤的情况:
ax.yaxis.set_minor_formatter(
plt.FormatStrFormatter('%.1f')
)
在这种情况下如何获得更好的控制的任何想法?
答案 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()