Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib figure with logarithmic axis but ticks without scientific/exponential notation [duplicate]

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)

enter image description here

like image 684
aph Avatar asked Mar 08 '23 11:03

aph


2 Answers

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

enter image description here

like image 115
ImportanceOfBeingErnest Avatar answered Mar 11 '23 04:03

ImportanceOfBeingErnest


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.

like image 33
Bennett Brown Avatar answered Mar 11 '23 06:03

Bennett Brown