matplotlib 对数轴大小刻度

xmd2e60i  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(138)

在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,)))

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

fsi0uk1n

fsi0uk1n1#

您可以使用MultipleLocator设置刻度的位置。您可以使用ax.xaxis.set_major_locatorax.xaxis.set_minor_locator为主刻度和次刻度设置不同的倍数。
至于刻度标签的格式:您可以使用ax.xaxis.set_major_formatterScalarFormatter设置主刻度格式,并使用ax.xaxis.set_minor_formatterNullFormatter关闭次刻度标签。
举例来说:

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

cmssoen2

cmssoen22#

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

相关问题