Search code examples
pythonmatplotlibimshowxticks

arrange values and labels on plots yticks-xticks


enter image description here

height_str=headers[1:]   #height format str
height=[float(i) for i in height_str]  #height format float -type:LIST

plt.yticks((height),height_str)  #height  y axis

Hello. I would like to display the values and labels in a better range on the plot. I use imshow for the graph. height is a list that contains 156 elements


Solution

  • The way you supplied the ticks, you're telling matplotlib to place a tick at every height value you gave it. You need to give it only the specific ticks you want to use if you're doing things this way.

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.misc import face
    
    # Generating my face heights
    height = np.arange(0, 800)
    height_str = list(map(str, height))
    plt.imshow(face())
    #plt.yticks(height,height_str)  # <- this is bad. Do this instead
    plt.yticks(height[::50],height_str[::50]) # Gets every 50th entry
    

    Otherwise, you could do this:

    fig, ax = plt.subplots()
    ax.imshow(face())
    ax.set_yticks(height[::50])
    

    Edit: To format, you can use ticker functions.

    from matplotlib import ticker
    ax.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.2f}"))
    

    From https://matplotlib.org/stable/gallery/ticks_and_spines/tick-formatters.html