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

可紊 提交于 2019-11-27 20:59:53

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)

Here is another way:

from matplotlib.ticker import MaxNLocator

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

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!