I am making a figure where the x-axis should be logarithmically spaced, but I want to manually set the tick labels, and I want the tick labels to appear in ordinary '%.2f' notation, not exponential notation. The following solution based on Matplotlib - logarithmic scale, but require non-logarithmic labels suggests to use ScalarFormatter, but does not work with matplotlib 2.0:
x = np.logspace(2, 3, 100)
y = x
fig, ax = plt.subplots(1, 1)
xscale = ax.set_xscale('log')
ax.set_xticks((100, 200, 300, 500))
xlim = ax.set_xlim(100, 1000)
from matplotlib.ticker import ScalarFormatter
ax.get_xaxis().set_major_formatter(ScalarFormatter())
__=ax.plot(x, y)
The use of a ScalarFormatter
is sure possible. You would then need to make sure that no minor ticklabels are shown as seen in this question: Matplotlib: setting x-limits also forces tick labels?
In your case the code would then look like:
import matplotlib.pyplot as plt
import numpy as np
x = np.logspace(2, 3, 100)
y = x
fig, ax = plt.subplots(1, 1)
xscale = ax.set_xscale('log')
ax.set_xticks((100, 200, 300, 500))
xlim = ax.set_xlim(100, 1000)
import matplotlib.ticker
ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax.get_xaxis().set_minor_formatter(matplotlib.ticker.NullFormatter())
__=ax.plot(x, y)
plt.show()
Because you are hard-coding the min and max for the axis, it looks like you are trying to create the graph one-off rather than programatically for more general data. In this case, and especially because you are already getting a reference to the x-xais, you could place the tick label strings in a list and use the axis method set_ticklabels
. In general, see the API for axis and tick objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With