2012-06-29 48 views
14

很多時候我想製作一個計數的條形圖。如果計數很低,我經常會得到不是整數的主要和/或次要滴答位置。我怎樣才能防止這一點?當數據計數時,在1.5處打勾是沒有意義的。python matplotlib限制爲整數刻度位置

這是我第一次嘗試:

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

我如何獲得第一個例子的期望行爲與小數量同時避免發生在第二個?

+0

這被錯誤地標記爲重複。有人問另一個問題。另一個問題應該是標記爲重複的問題。 – John

回答

24

可以使用MaxNLocator方法,像這樣:

from pylab import MaxNLocator 

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

我相信'pylab.MaxNLocator()'是更好的表示法。 – FooBar

+2

或者如果你沒有導入pylab,'matplotlib.ticker.MaxNLocator()'。 (來自[這個答案](http://stackoverflow.com/a/27496811/2452770)) –

0

我想事實證明,我可以忽略次要的蜱蟲。我想給這個一去,看看它是否在所有的情況站起來:

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() 
2
pylab.bar(range(1,4), range(1,4), align='center') 

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

已在我的代碼中工作。 只需使用align可選參數和xticks即可。

+0

這種方法不會給太大的範圍提供太多的滴答聲嗎? – John