Search code examples
pythonseabornheatmapaxis-labelsyaxis

How to rotate Seaborn heatmap in python?


default settings of seaborn.heatmap gives

enter image description here

  • the x-axis starts from the origin of 0 then increases towards the right
  • the y-axis starts from an origin of 9 then increases towards the upward

This is odd compared to matplotlib.pyplot.pcolormesh, which gives a y-axis that starts from an origin of 0 that moves upward, like what we'd intuitively want since it only makes sense for origins to be (0,0), not (0,9)!

How to make the y-axis of heatmap also start from an origin of 0, instead of 9, moving upward? (while of course re-orienting the data correspondingly)

I tried transposing the input data, but this doesn't look right and the axes don't change. I don't think it's a flip about the y-axis that's needed, but a simple rotating of the heatmap.


Solution

  • You can flip the y-axis using ax.invert_yaxis():

    import seaborn as sns
    import numpy as np
    np.random.seed(0)
    
    sns.set_theme()
    uniform_data = np.random.rand(10, 12)
    ax = sns.heatmap(uniform_data)
    ax.invert_yaxis()
    

    If you want to do the rotation you describe, you have to transpose the matrix first:

    import seaborn as sns
    import numpy as np
    np.random.seed(0)
    
    sns.set_theme()
    uniform_data = np.random.rand(10, 12)
    ax = sns.heatmap(uniform_data.T)
    ax.invert_yaxis()
    

    The reason for the difference is that they are assuming different coordinate systems. pcolormesh is assuming that you want to access the elements using cartesian coordinates i.e. [x, y] and it displays them in the way you would expect. heatmap is assuming you want to access the elements using array coordinates i.e. [row, col], so the heatmap it gives has the same layout as if you print the array to the console.

    Why do they use different coordinate systems? I would be speculating but I think it's due to the ages of the 2 libraries. matplotlib, particularly its older commands is a port from Matlab, so many of the assumptions are the same. seaborn was developed for Python much later, specifically aimed at statistical visualization, and after pandas was already existent. So I would guess that mwaskom chose the layout to replicate how a DataFrame looks when you print it to the screen.