1

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 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

ax.semilogx() is a plotting function (i.e. analogous to ax.plot()), which also sets the scale of the x-axis to logarithmic. If all you want to do is change the x-axis scale, there is a dedicated function for that: ax.set_xscale('log')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.