2012-06-29 17 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)) 

カウントは小さいですが、彼らが大きい場合、私は多くの多くの小目盛りを取得するときに、[OK]作品:

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

はどうやって取得することができます第2の例で何が起こるのを避けながら、小さなカウントで最初の例からの望ましい動作?

+0

これは誤って重複としてマークされています。それは他の質問の前に尋ねられました。他の質問は、重複としてマークされたものでなければなりません。 – John

答えて

24

あなたがそうのように、MaxNLocator方法を使用することができます。

from pylab import MaxNLocator 

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

私は 'pylab.MaxNLocator()'がより良い記法であると信じています。 – FooBar

+2

、またはピラブをインポートしない場合は、 '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

関連する問題