0

Suppose I had the following code:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(520)
y = np.random.rand(520)
plt.plot(x, y)

which produces the following graph:

enter image description here

How can I define a custom axis so my X-axis looks like this:

enter image description here

1 Answer 1

4

You can use:

  • plt.xscale('log') to change the scale to a log scale
  • set_major_formatter(ScalarFormatter()) to set the formatting back to normal (replacing the LogFormatter)
  • set_minor_locator(NullLocator()) to remove the minor ticks (that were also set by the log scale)
  • set_major_locator(FixedLocator([...] or plt.xticks([...]) to set the desired ticks on the x-axis
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter, NullLocator, FixedLocator
import numpy as np

x = np.arange(520)
y = np.random.uniform(-1, 1, 520).cumsum()
plt.plot(x, y)
plt.xscale('log')
# plt.xticks([...])
plt.gca().xaxis.set_major_locator(FixedLocator([2**i for i in range(0, 7)] + [130, 260, 510]))
plt.gca().xaxis.set_major_formatter(ScalarFormatter())
plt.gca().xaxis.set_minor_locator(NullLocator())
plt.show()

example plot

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

Comments

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.