对数轴主要和次要刻度线

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

在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
2个回答
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()

0
投票

您可以使用

MultipleLocator
设置刻度的位置。您可以使用
ax.xaxis.set_major_locator
ax.xaxis.set_minor_locator
为主要和次要刻度设置不同的倍数。

至于刻度标签的格式:您可以使用

ax.xaxis.set_major_formatter
ScalarFormatter
设置主要刻度格式,并使用
ax.xaxis.set_minor_formatter
NullFormatter
关闭次要刻度标签.

例如:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# set the xaxis to a logarithmic scale
ax.set_xscale('log')

# set the desired axis limits
ax.set_xlim(1, 4.5)

# set the spacing of the major ticks to 0.5
ax.xaxis.set_major_locator(plt.MultipleLocator(0.5))

# set the format of the major tick labels
ax.xaxis.set_major_formatter(plt.ScalarFormatter())

# set the spacing of the minor ticks to 0.1
ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))

# turn off the minor tick labels
ax.xaxis.set_minor_formatter(plt.NullFormatter())

plt.show()

© www.soinside.com 2019 - 2024. All rights reserved.