How to force the Y axis to only use integers in Matplotlib?

PythonMatplotlibAxis Labels

Python Problem Overview


I'm plotting a histogram using the matplotlib.pyplot module and I am wondering how I can force the y-axis labels to only show integers (e.g. 0, 1, 2, 3 etc.) and not decimals (e.g. 0., 0.5, 1., 1.5, 2. etc.).

I'm looking at the guidance notes and suspect the answer lies somewhere around matplotlib.pyplot.ylim but so far I can only find stuff that sets the minimum and maximum y-axis values.

def doMakeChart(item, x):
    if len(x)==1:
        return
    filename = "C:\Users\me\maxbyte3\charts\\"
    bins=logspace(0.1, 10, 100)
    plt.hist(x, bins=bins, facecolor='green', alpha=0.75)
    plt.gca().set_xscale("log")
    plt.xlabel('Size (Bytes)')
    plt.ylabel('Count')
    plt.suptitle(r'Normal Distribution for Set of Files')
    plt.title('Reference PUID: %s' % item)
    plt.grid(True)
    plt.savefig(filename + item + '.png')
    plt.clf()

Python Solutions


Solution 1 - Python

Here is another way:

from matplotlib.ticker import MaxNLocator

ax = plt.figure().gca()
ax.yaxis.set_major_locator(MaxNLocator(integer=True))

Solution 2 - Python

If you have the y-data

y = [0., 0.5, 1., 1.5, 2., 2.5]

You can use the maximum and minimum values of this data to create a list of natural numbers in this range. For example,

import math
print range(math.floor(min(y)), math.ceil(max(y))+1)

yields

[0, 1, 2, 3]

You can then set the y tick mark locations (and labels) using matplotlib.pyplot.yticks:

yint = range(min(y), math.ceil(max(y))+1)

matplotlib.pyplot.yticks(yint)

Solution 3 - Python

this works for me:

import matplotlib.pyplot as plt
plt.hist(...

# make the y ticks integers, not floats
yint = []
locs, labels = plt.yticks()
for each in locs:
	yint.append(int(each))
plt.yticks(yint)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJay GattusoView Question on Stackoverflow
Solution 1 - PythongalathView Answer on Stackoverflow
Solution 2 - PythonChrisView Answer on Stackoverflow
Solution 3 - PythonOfer ChayView Answer on Stackoverflow