如何强制Y轴在Matplotlib中仅使用整数?

2024-04-25 15:57:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用matplotlib.pyplot模块绘制直方图,我想知道如何强制y轴标签只显示整数(如0、1、2、3等),而不显示小数(如0、0.5、1、1.5、2)。等等)。

我在看指导说明,怀疑答案就在matplotlib.pyplot.ylim附近,但到目前为止,我只能找到设置最小和最大y轴值的东西。

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

Tags: 模块答案matplotlib绘制plt整数标签直方图
3条回答

这是另一种方式:

from matplotlib.ticker import MaxNLocator

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

这对我有效:

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)

如果你有y数据

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

可以使用此数据的最大值和最小值创建此范围内的自然数列表。例如

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

收益率

[0, 1, 2, 3]

然后,可以使用matplotlib.pyplot.yticks设置y记号位置(和标签):

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

matplotlib.pyplot.yticks(yint)

相关问题 更多 >

    热门问题