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

2 番目の例で起こることを回避しながら、小さなカウントで最初の例から望ましい動作を取得するにはどうすればよいですか?

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 に答える
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 に答える