Marcelo Villa
Marcelo Villa

Reputation: 1131

How to define custom axis in Matplotlib?

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

Upvotes: 0

Views: 462

Answers (1)

JohanC
JohanC

Reputation: 80329

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

Upvotes: 4

Related Questions