Pandas DataFrame Plot Heatmap using Seaborn

visibility 1,839 event 2022-06-04 access_time 6 months ago language English
more_vert
Pandas DataFrame Plot Heatmap using Seaborn

Heatmaps can be used to visualize data in a colored matrix. One typical use case is to visualize website clicks by date and hour. This article uses seaborn Python package to plot a heatmap chart. Jupyter notebook is used as the tool.

Import required packages

First, let's import the required packages:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from datetime import date, timedelta
import random

If seaborn package is not available in your Python environment, install it using the following command:

pip install seaborn
# or 
pip3 install seaborn

If you are using Anaconda, you can directly add it into your Anaconda environment.

Create a sample DataFrame

Now let's create a DataFrame object in memory directly using code:

# Populate sample data
data= []
start_date = date(2022,1,1)
start_hour = 0
for i in range(0,7):
    start_date += timedelta(days=i)
    print(start_date)
    for j in range(0,24):
        clicks = random.randint(0, 10000)
        data.append({"date":start_date,"hour": j, "clicks": clicks})
df = pd.DataFrame(data)
df.reset_index(drop=True)

The prepared DataFrame looks like the following table:

datehourclicks
02022-01-0102517
12022-01-0111242
22022-01-0121428
32022-01-0133495
42022-01-0147880
............
1632022-01-22193025
1642022-01-2220664
1652022-01-222171
1662022-01-22221603
1672022-01-22236141

168 rows × 3 columns

Visualize using seaborn

Now, convert the DataFrame to a pivot table for visualize:

df1 = df[['hour','date','clicks']]
x = pd.DataFrame(df1['date'].unique())
heatmap_pt = pd.pivot_table(df1,values ='clicks', index=['hour'], columns='date')
headmap_pt

The pivoted table can be used to plot the chart:

fig, ax = plt.subplots(figsize=(16,8))
sns.set()
sns.heatmap(heatmap_pt, cmap='YlGnBu')
plt.xticks(rotation=15)
plt.show()

The output looks like the following screenshot:

2022060463206-image.png

Seaborn can be used to plot many other different types of chart. Refer to seaborn: statistical data visualization for more details. 

info Last modified by Administrator 6 months ago copyright This page is subject to Site terms.
Like this article?
Share on

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts