Matplotlib: How to force integer tick labels?

后端 未结 2 1125
谎友^
谎友^ 2020-12-05 09:06

My python script uses matplotlib to plot a 2D \"heat map\" of an x, y, z dataset. My x- and y-values represent amino acid residues in a protein and can therefore only be int

相关标签:
2条回答
  • 2020-12-05 09:56

    This should be simpler:

    (from https://scivision.co/matplotlib-force-integer-labeling-of-axis/)

    import matplotlib.pyplot as plt
    from matplotlib.ticker import MaxNLocator
    #...
    ax = plt.figure().gca()
    #...
    ax.xaxis.set_major_locator(MaxNLocator(integer=True))
    
    0 讨论(0)
  • 2020-12-05 10:04

    Based on an answer for modifying tick labels I came up with a solution, don't know whether it will work in your case as your code snippet can't be executed in itself.

    The idea is to force the tick labels to a .5 spacing, then replace every .5 tick with its integer counterpart, and others with an empty string.

    import numpy
    import matplotlib.pyplot as plt
    
    fig, (ax1, ax2) = plt.subplots(1,2)
    
    x1, x2 = 1, 5
    y1, y2 = 3, 7
    
    # first axis: ticks spaced at 0.5
    ax1.plot([x1, x2], [y1, y2])
    ax1.set_xticks(numpy.arange(x1-1, x2+1, 0.5))
    ax1.set_yticks(numpy.arange(y1-1, y2+1, 0.5))
    
    # second axis: tick labels will be replaced
    ax2.plot([x1, x2], [y1, y2])
    ax2.set_xticks(numpy.arange(x1-1, x2+1, 0.5))
    ax2.set_yticks(numpy.arange(y1-1, y2+1, 0.5))
    
    # We need to draw the canvas, otherwise the labels won't be positioned and 
    # won't have values yet.
    fig.canvas.draw()
    
    # new x ticks  '1'->'', '1.5'->'1', '2'->'', '2.5'->'2' etc.
    labels = [item.get_text() for item in ax2.get_xticklabels()]
    new_labels = [ "%d" % int(float(l)) if '.5' in l else '' for l in labels]
    ax2.set_xticklabels(new_labels)
    
    # new y ticks
    labels = [item.get_text() for item in ax2.get_yticklabels()]
    new_labels = [ "%d" % int(float(l)) if '.5' in l else '' for l in labels]
    ax2.set_yticklabels(new_labels)
    
    fig.canvas.draw()
    plt.show()
    

    If you want to zoom out a lot, that will need some extra care, as this one produces a very dense set of tick labels then.

    0 讨论(0)
提交回复
热议问题