Sunday, 18 May 2025

Time Scale Heatmap Pattern using Python

 


import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

days = pd.date_range("2025-05-18", periods=7, freq="D")

hours = np.arange(24)

data = np.random.rand(len(days), len(hours))

df = pd.DataFrame(data, index=days.strftime('%a %d'), columns=hours)

plt.figure(figsize=(8, 6))

plt.imshow(df, aspect='auto', cmap='YlGnBu')

plt.xticks(ticks=np.arange(len(hours)), labels=hours)

plt.yticks(ticks=np.arange(len(days)), labels=df.index)

plt.xlabel("Hour of Day")

plt.ylabel("Date")

plt.title("Timescale Heatmap (Hourly Activity Over a Week)")

plt.colorbar(label='Intensity')

plt.tight_layout()

plt.show()

#source code --> clcoding.com

Code Explanation:

1. Import Required Libraries

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

numpy: For creating numerical data (e.g., rand, arange).

pandas: Used for handling time-series and tabular data (DataFrame, date_range).

matplotlib.pyplot: For creating the actual heatmap plot.

 

2. Define Time Axes: Days & Hours

days = pd.date_range("2025-05-01", periods=7, freq="D")

hours = np.arange(24)

pd.date_range(...): Creates 7 sequential days starting from May 1, 2025.

 

np.arange(24): Creates an array [0, 1, ..., 23] representing each hour in a day.

These will become the y-axis (days) and x-axis (hours) of the heatmap.

 

3. Simulate Random Data

data = np.random.rand(len(days), len(hours))

Generates a 7×24 matrix of random numbers between 0 and 1.

Each value represents some measurement (e.g., activity level, temperature) at a specific hour on a specific day.

 

4. Create a Pandas DataFrame

df = pd.DataFrame(data, index=days.strftime('%a %d'), columns=hours)

Converts the NumPy array into a labeled table.

index=days.strftime('%a %d'): Formats each date like 'Thu 01', 'Fri 02' etc.

columns=hours: Sets hours (0–23) as column headers.

This structure is perfect for feeding into a heatmap.

 

5. Create the Heatmap

plt.figure(figsize=(12, 6))

plt.imshow(df, aspect='auto', cmap='YlGnBu')

plt.figure(...): Sets the size of the figure (12x6 inches).

plt.imshow(...): Plots the DataFrame as a 2D image (the heatmap).

aspect='auto': Automatically scales the plot height.

cmap='YlGnBu': Applies a yellow-green-blue colormap.

Each cell's color intensity represents the magnitude of the data value.

 

6. Add Axes Labels and Ticks

plt.xticks(ticks=np.arange(len(hours)), labels=hours)

plt.yticks(ticks=np.arange(len(days)), labels=df.index)

plt.xlabel("Hour of Day")

plt.ylabel("Date")

plt.title("Timescale Heatmap (Hourly Activity Over a Week)")

xticks/yticks: Places numeric hour labels on the x-axis and day labels on the y-axis.

xlabel, ylabel, title: Adds descriptive text to explain what the axes and plot represent.

 

7. Add Colorbar

plt.colorbar(label='Intensity')

Adds a color legend (colorbar) on the side.

Helps interpret what the color shading corresponds to (e.g., higher activity = darker color).

 

8. Final Touches and Display

plt.tight_layout()

plt.show()

tight_layout(): Adjusts spacing to prevent overlaps.

 show(): Displays the plot window.


0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (152) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (217) Data Strucures (13) Deep Learning (68) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (186) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1218) Python Coding Challenge (884) Python Quiz (342) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)