Python Matplotlib限制为整数刻度位置 [英] Python matplotlib restrict to integer tick locations

查看:616
本文介绍了Python Matplotlib限制为整数刻度位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常想制作一个条形图.如果计数很低,我经常会得到不是整数的主要和/或次要刻度位置.我该如何预防呢?当数据计数时,在1.5处打勾是没有意义的.

Quite often I want to make a bar chart of counts. If the counts are low I often get major and/or minor tick locations that are not integers. How can I prevent this? It makes no sense to have a tick at 1.5 when the data are counts.

这是我的第一次尝试:

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

当计数较小时可以正常工作,但是当计数较大时,我会得到很多次要的滴答声:

which works OK when the counts are small but when they are large, I get many many minor ticks:

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

如何从第一个示例中获得少量期望的行为,同时避免第二个示例中发生的事情?

How can I get the desired behaviour from the first example with small counts whilst avoiding what happens in the second?

推荐答案

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

You can use the MaxNLocator method, like so:

    from pylab import MaxNLocator

    ya = axes.get_yaxis()
    ya.set_major_locator(MaxNLocator(integer=True))

这篇关于Python Matplotlib限制为整数刻度位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆