Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matplotlib heatmap axis labels not aligned correctly with cells

Here is the code I’m using for generating heatmap:

    import numpy as np
    import matplotlib.pyplot as plt

    x_values = [x for x in range(5)]
    y_values = [y for y in range(7)]
    z_values = np.random.rand(len(y_values), len(x_values))
    plt.imshow(z_values, cmap='viridis', extent=[min(x_values), max(x_values), min(y_values), max(y_values)],
               origin='lower', aspect='auto')

    plt.gca().invert_yaxis()

    # Add labels for every y-axis point and every second x-axis point
    plt.yticks(np.arange(len(y_values)), y_values)
    plt.xticks(np.arange(0, len(x_values), 2), x_values[::2])

    plt.show()

This is example result:Generated heatmap

It is clear that x-axis and y-axis labels are misarranged. How do I fix this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just change

extent=[min(x_values), max(x_values), min(y_values), max(y_values)]

to

extent=[min(x_values), max(x_values) + 1, min(y_values), max(y_values) + 1]

in the call to imshow.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading