Search code examples
pythonmatplotlibgraphseabornheatmap

How to create a heatmap in Python with 3 columns - the x and y coordinates and the heat


I have a dataframe with 3 columns, x-points, y-points and the heat. Like this:

X, Y, Z
-2, 0, 1
-2, 1, 2
-2, 2, 5
-1, 0, 3
-1, 1, 5
-1, 2, 8
.., .., ..
2, 1, 4
2, 2, 1

I want to plot a heatmap of this data with X and Y being the coords, and Z being the heat.

I have tried lots of ways to do this and constantly run into different errors.


Solution

  • Use pivot and seaborn.heatmap:

    import seaborn as sns
    
    sns.heatmap(df.pivot(index='Y', columns='X', values='Z'))
    

    Output:

    enter image description here

    IF you want to handle missing coordinates:

    df2 = (df
       .pivot(index='Y', columns='X', values='Z')
       .pipe(lambda d: d.reindex(index=range(d.index.min(), d.index.max()+1),
                                 columns=range(d.columns.min(), d.columns.max()+1),
                                )
            )
    )
    
    sns.heatmap(df2)
    

    Output:

    enter image description here