python matplotlib 对数轴主要刻度和次要刻度

问题描述 投票:0回答:1

只是想知道在python的matplotlib中,如何使对数x轴刻度如附图所示(即,从1到4.5每隔0.5个间距有标签的主要刻度;每0.1个间距没有标签的次要刻度):

我尝试过一些方法,例如

ax1.set_xticks([1.5,2,2.5,3,3.5,4,4.5])
ax1.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
ax1.xaxis.set_minor_locator(LogLocator(base=1,subs=(0.1,)))

但它没有给我正确的解决方案。

python matplotlib logarithm xticks
1个回答
0
投票
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.semilogx()

a, b = 1, 4.5
step_minor, step_major = 0.1, 0.5

minor_xticks = np.arange(a, b + step_minor, step_minor)
ax.set_xticks(minor_xticks, minor=True)
ax.set_xticklabels(["" for _ in minor_xticks], minor=True)

xticks = np.arange(a, b + step_major, step_major)
ax.set_xticks(xticks)
ax.set_xticklabels(xticks)


ax.set_xlim([a, b])

plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.