Python matplotlib restrict to integer tick locations

后端 未结 3 1349
我寻月下人不归
我寻月下人不归 2020-11-29 11:15

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

相关标签:
3条回答
  • 2020-11-29 11:35
     pylab.bar(range(1,4), range(1,4), align='center')  
    

    and

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

    has worked in my code. Just use the align optional parameter and xticks does the magic.

    0 讨论(0)
  • 2020-11-29 11:38

    You can use the MaxNLocator method, like so:

        from pylab import MaxNLocator
    
        ya = axes.get_yaxis()
        ya.set_major_locator(MaxNLocator(integer=True))
    
    0 讨论(0)
  • 2020-11-29 11:54

    I think it turns out I can just ignore the minor ticks. I'm going to give this a go and see if it stands up in all use cases:

    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()
    
    0 讨论(0)
提交回复
热议问题