How To Force Matplotlib To Display Only Whole Numbers On The Y Axis
Solution 1:
The most flexible way is to specify integer=True
to the default tick locator (MaxNLocator
) do something similar to this:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
fig, ax = plt.subplots()
# Be sure to only pick integer tick locations.
for axis in [ax.xaxis, ax.yaxis]:
axis.set_major_locator(ticker.MaxNLocator(integer=True))
# Plot anything (note the non-integer min-max values)...
x = np.linspace(-0.1, np.pi, 100)
ax.plot(0.5 * x, 22.8 * np.cos(3 * x), color='black')
# Just for appearance's sake
ax.margins(0.05)
ax.axis('tight')
fig.tight_layout()
plt.show()
Alternatively, you can manually set the tick locations/labels as Marcin and Joel suggest (or use a MultipleLocator
). The downside to this is that you need to work out what tick positions make sense, rather than having matplotlib pick a reasonable integer tick interval based on the axis limits.
Solution 2:
If it's just the yaxis you want to change, an easy way is to determine which ticks you want:
tickpos = [0,1,4,6]
py.yticks(tickpos,tickpos)
will put ticks at 0, 1, 4, and 6. More generally
py.yticks([0,1,2,3], ['zero', 1, 'two', 3.0])
will put the label of the second list at the location in the first list. If the label is going to be the yvalue, it's a good idea to use the py.yticks(tickpos,tickpos)
version just to make sure that whenever you change the locations of the ticks, the labels get the same change.
More generally though, Kington's answer will let you tell pylab just integers for the y axis, but let it choose where the ticks go.
Solution 3:
Another way of forcing integer ticks is to use pyplot.locator_params
.
Using almost the same example as in the accepted answer:
import numpy as np
import matplotlib.pyplot as plt
# Plot anything (note the non-integer min-max values)...
x = np.linspace(-0.1, np.pi, 100)
plt.plot(0.5 * x, 22.8 * np.cos(3 * x), color='black')
# use axis={'both', 'x', 'y'} to choose axis
plt.locator_params(axis="both", integer=True, tight=True)
# Just for appearance's sake
plt.margins(0.05)
plt.tight_layout()
plt.show()
Solution 4:
You can modify tick labels/numbers as follows. This is example only, as you have not provided any code that you have, so not sure if it applys to you or not.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.canvas.draw()
# just the original labels/numbers and modify them, e.g. multiply by 100
# and define new format for them.
labels = ["{:0.0f}".format(float(item.get_text())*100)
for item in ax.get_xticklabels()]
ax.set_xticklabels(labels)
plt.show()
Without modification of x axis:
WIth the modification:
Post a Comment for "How To Force Matplotlib To Display Only Whole Numbers On The Y Axis"