30

我经常想做一个计数条形图。如果计数很低,我经常会得到不是整数的主要和/或次要刻度位置。我怎样才能防止这种情况?当数据计数时,在 1.5 处打勾是没有意义的。

这是我的第一次尝试:

import pylab
pylab.figure()
ax = pylab.subplot(2, 2, 1)
pylab.bar(range(1,4), range(1,4), align='center')
major_tick_locs = ax.yaxis.get_majorticklocs()
if len(major_tick_locs) < 2 or major_tick_locs[1] - major_tick_locs[0] < 1:
    ax.yaxis.set_major_locator(pylab.MultipleLocator(1))
minor_tick_locs = ax.yaxis.get_minorticklocs()
if len(minor_tick_locs) < 2 or minor_tick_locs[1] - minor_tick_locs[0] < 1:
    ax.yaxis.set_minor_locator(pylab.MultipleLocator(1))

当计数很小但当它们很大时,它可以正常工作,我会得到很多小滴答声:

import pylab
ax = pylab.subplot(2, 2, 2)
pylab.bar(range(1,4), range(100,400,100), align='center')
major_tick_locs = ax.yaxis.get_majorticklocs()
if len(major_tick_locs) < 2 or major_tick_locs[1] - major_tick_locs[0] < 1:
    ax.yaxis.set_major_locator(pylab.MultipleLocator(1))
minor_tick_locs = ax.yaxis.get_minorticklocs()
if len(minor_tick_locs) < 2 or minor_tick_locs[1] - minor_tick_locs[0] < 1:
    ax.yaxis.set_minor_locator(pylab.MultipleLocator(1))

如何从第一个示例中获得所需的行为,同时避免第二个示例中发生的情况?

4

4 回答 4

38

您可以使用该MaxNLocator方法,如下所示:

    from pylab import MaxNLocator

    ya = axes.get_yaxis()
    ya.set_major_locator(MaxNLocator(integer=True))
于 2012-07-10T16:18:29.983 回答
3

我想事实证明我可以忽略小蜱。我将试一试,看看它是否适用于所有用例:

def ticks_restrict_to_integer(axis):
    """Restrict the ticks on the given axis to be at least integer,
    that is no half ticks at 1.5 for example.
    """
    from matplotlib.ticker import MultipleLocator
    major_tick_locs = axis.get_majorticklocs()
    if len(major_tick_locs) < 2 or major_tick_locs[1] - major_tick_locs[0] < 1:
        axis.set_major_locator(MultipleLocator(1))

def _test_restrict_to_integer():
    pylab.figure()
    ax = pylab.subplot(1, 2, 1)
    pylab.bar(range(1,4), range(1,4), align='center')
    ticks_restrict_to_integer(ax.xaxis)
    ticks_restrict_to_integer(ax.yaxis)

    ax = pylab.subplot(1, 2, 2)
    pylab.bar(range(1,4), range(100,400,100), align='center')
    ticks_restrict_to_integer(ax.xaxis)
    ticks_restrict_to_integer(ax.yaxis)

_test_restrict_to_integer()
pylab.show()
于 2012-06-29T08:16:54.423 回答
3

I had a similar issue with a histogram I was plotting showing fractional count. Here's how I was able to resolve it:

plt.hist(x=[Dataset being counted])

# Get your current y-ticks (loc is an array of your current y-tick elements)
loc, labels = plt.yticks()

# This sets your y-ticks to the specified range at whole number intervals
plt.yticks(np.arange(0, max(loc), step=1))
于 2021-03-08T23:19:30.543 回答
2
 pylab.bar(range(1,4), range(1,4), align='center')  

 xticks(range(1,40),range(1,40))

在我的代码中工作过。只需使用align可选参数并发挥xticks作用。

于 2012-08-21T12:17:47.663 回答