Create a Python Heatmap with Seaborn
You can easily create a heatmap using the Seaborn library in Python. For this tutorial, I’m going to create this using Jupyter Notebooks. The first step is to load the dependencies which are the essential library. You can also Learn Python Data Insights on YouTube
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
Now that we have the essential libraries, let’s load in your data set and save it as a variable called df. My data is saved as a CSV. I am going to use Avocado prices I download from Kaggle’s data library.
df = pd.read_csv('avocado.csv')
How does Seaborn Heatmap work?
This heat map works by correlation. This shows you which variables are correlated to each other from a scale of 1 being the most correlated and -1 is not correlated at all. However, you cannot correlate strings. You can only correlate numerical features. Don’t let this stop you because you can always encode your categorical data types using the get_dummies function in Pandas library. I am adding the figure size so that we get a bigger image. You can do this by adding plt.figure() function.
Once you have the heat map created, let’s make it more actionable by changing the styles. Add correlation numbers to get a better understanding of it. You can do this by adding the annot parameter which will add correlation numbers to each cell in the visuals.
We can style this further by changing the figure size and colors. To do this you will need to use Matplotlib figure function.
Add Lines between the correlation cells
Change the Heatmap Colors
Lastly, you can alter the colors of your heatmap by utilizing the cmap parameter. You can Google the Seaborn color palette to see what is available. I’m going to change this to the coolwarm palette. Here is a great resource for colors
plt.figure(figsize=(9,5)sns.heatmap(df.corr(),annot=True,linewidth = 0.5, cmap='coolwarm')
Check out the Video on Seaborn Heatmap Creation, Sub Plots, and Other Visuals
It’s great to see some essential functions in such an easy-to-follow way – thanks!
BUT: it would be even more great, if the code parts (which are copyable) were correct (no wrong function names, missing brackets and typos) 😉
Thanks for pointing that out. Corrected
some bracket error
I’ve got some issue if I make few pictures in row, the each next picture shows the old numbers from previous pictures.
Do i something wrong?
May you guide me please?
Have nice day!