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.


0 Comments:
Post a Comment