Python matplotlib限制为整数刻度位置

2024-05-14 09:38:17 发布

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

我经常想做一个计数的柱状图。如果计数很低,我通常会得到非整数的主要和/或次要刻度位置。我怎样才能防止这种情况?在计算数据时,在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))

如何从第一个例子中获得期望的行为,同时避免在第二个例子中发生什么?


Tags: orgetlenifrangeax计数set
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()

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

    from pylab import MaxNLocator

    ya = axes.get_yaxis()
    ya.set_major_locator(MaxNLocator(integer=True))
 pylab.bar(range(1,4), range(1,4), align='center')  

以及

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

在我的代码中起作用。 只要使用align可选参数,xticks就有了魔力。

相关问题 更多 >

    热门问题