logarithmic axis major and minor ticks

120 Views Asked by At

In python's matplotlib, how can I make the logarithm x-axis ticks as the attached picture shows (i.e., major ticks with labels at every 0.5 spacing from 1 to 4.5; minor ticks without labels at every 0.1 spacing):

The appearance of final logarithm ticks

I've tried some methods such as

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

But it doesn't give me the right solution.

2

There are 2 best solutions below

0
tmdavison On BEST ANSWER

You can set the location of the ticks using a MultipleLocator. You can set a different multiple for the major and minor ticks using ax.xaxis.set_major_locator and ax.xaxis.set_minor_locator.

As for the formatting of the tick labels: you can set the major tick format using ax.xaxis.set_major_formatter with a ScalarFormatter and turn off the minor tick labels using ax.xaxis.set_minor_formatter with a NullFormatter.

For example:

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

enter image description here

1
Roman Pavelka On
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()