Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 108 additions & 33 deletions plots/heatmap-basic/implementations/altair.py
Original file line number Diff line number Diff line change
@@ -1,66 +1,141 @@
""" pyplots.ai
heatmap-basic: Basic Heatmap
Library: altair 6.0.0 | Python 3.13.11
Quality: 91/100 | Created: 2025-12-23
Library: altair 6.0.0 | Python 3.14.3
Quality: 88/100 | Updated: 2026-02-16
"""

import altair as alt
import numpy as np
import pandas as pd


# Data - create a matrix with patterns
# Data - correlation matrix with realistic weather variables
np.random.seed(42)
rows = ["Row A", "Row B", "Row C", "Row D", "Row E", "Row F", "Row G", "Row H"]
cols = ["Col 1", "Col 2", "Col 3", "Col 4", "Col 5", "Col 6", "Col 7", "Col 8"]
variables = [
"Temperature",
"Humidity",
"Wind Speed",
"Pressure",
"Visibility",
"Cloud Cover",
"Precipitation",
"UV Index",
]

# Generate values with some patterns (diagonal pattern + noise)
values = []
for i, row in enumerate(rows):
for j, col in enumerate(cols):
# Create pattern: higher values near diagonal, add noise
base = 100 - abs(i - j) * 12
noise = np.random.randn() * 10
values.append({"x": col, "y": row, "value": base + noise})
n_samples = 200
raw = np.random.randn(n_samples, len(variables))

df = pd.DataFrame(values)
# Inject realistic correlations with stronger relationships
raw[:, 1] += raw[:, 0] * 0.6 # Humidity ~ Temperature
raw[:, 5] += raw[:, 1] * 0.7 # Cloud Cover ~ Humidity
raw[:, 6] += raw[:, 5] * 0.65 # Precipitation ~ Cloud Cover
raw[:, 4] -= raw[:, 5] * 0.9 # Visibility inversely ~ Cloud Cover
raw[:, 7] -= raw[:, 5] * 0.7 # UV Index inversely ~ Cloud Cover
raw[:, 7] += raw[:, 0] * 0.5 # UV Index ~ Temperature
raw[:, 3] -= raw[:, 0] * 0.4 # Pressure inversely ~ Temperature
raw[:, 2] += raw[:, 3] * 0.3 # Wind Speed ~ Pressure

# Plot - heatmap base
corr = np.corrcoef(raw.T)

# Build long-form dataframe using list comprehension
df = pd.DataFrame(
[
{"Row": row_var, "Column": col_var, "value": round(corr[i, j], 2)}
for i, row_var in enumerate(variables)
for j, col_var in enumerate(variables)
]
)

# Axis ordering
axis_order = list(variables)

# Plot - heatmap with colorblind-safe diverging color centered at 0
heatmap = (
alt.Chart(df)
.mark_rect()
.mark_rect(stroke="#ffffff", strokeWidth=1.5, cornerRadius=2)
.encode(
x=alt.X("x:N", title="Column", axis=alt.Axis(labelFontSize=16, titleFontSize=20)),
y=alt.Y("y:N", title="Row", axis=alt.Axis(labelFontSize=16, titleFontSize=20)),
x=alt.X(
"Column:N",
title="Weather Variable",
sort=axis_order,
axis=alt.Axis(
labelFontSize=15, titleFontSize=18, labelAngle=-45, orient="top", labelPadding=8, titlePadding=10
),
),
y=alt.Y(
"Row:N",
title="Weather Variable",
sort=axis_order,
axis=alt.Axis(labelFontSize=15, titleFontSize=18, labelPadding=8, titlePadding=10),
),
color=alt.Color(
"value:Q",
scale=alt.Scale(scheme="blueorange", domainMid=50),
legend=alt.Legend(title="Value", titleFontSize=18, labelFontSize=16),
scale=alt.Scale(scheme="blueorange", domain=[-1, 1], domainMid=0),
legend=alt.Legend(
title="Correlation",
titleFontSize=16,
labelFontSize=14,
gradientLength=300,
gradientThickness=16,
titlePadding=6,
offset=8,
direction="vertical",
),
),
tooltip=["x:N", "y:N", "value:Q"],
tooltip=[
alt.Tooltip("Column:N", title="Column"),
alt.Tooltip("Row:N", title="Row"),
alt.Tooltip("value:Q", title="Correlation", format=".2f"),
],
)
)

# Add text annotations
# Highlight cells with strong correlations using thicker borders
highlight = (
alt.Chart(df)
.transform_filter((alt.datum.value >= 0.7) | (alt.datum.value <= -0.7))
.mark_rect(stroke="#2a2a2a", strokeWidth=2.5, filled=False, cornerRadius=2)
.encode(x=alt.X("Column:N", sort=axis_order), y=alt.Y("Row:N", sort=axis_order))
)

# Text annotations with adaptive color
text = (
alt.Chart(df)
.mark_text(fontSize=18)
.mark_text(fontSize=15, fontWeight="bold")
.encode(
x=alt.X("x:N"),
y=alt.Y("y:N"),
text=alt.Text("value:Q", format=".0f"),
color=alt.condition(alt.datum.value > 70, alt.value("white"), alt.value("black")),
x=alt.X("Column:N", sort=axis_order),
y=alt.Y("Row:N", sort=axis_order),
text=alt.Text("value:Q", format=".2f"),
color=alt.when((alt.datum.value > 0.55) | (alt.datum.value < -0.55))
.then(alt.value("#ffffff"))
.otherwise(alt.value("#333333")),
)
)

# Combine heatmap and text, then apply configuration
# Combine layers and configure
chart = (
(heatmap + text)
.properties(width=1400, height=800, title=alt.Title("heatmap-basic · altair · pyplots.ai", fontSize=28))
.configure_axis(labelFontSize=16, titleFontSize=20, grid=False)
(heatmap + highlight + text)
.properties(
width=740,
height=766,
title=alt.Title(
"heatmap-basic · altair · pyplots.ai",
subtitle=[
"Pairwise Pearson correlation coefficients for 8 weather metrics.",
"Bold borders highlight strong relationships (|r| ≥ 0.7).",
],
fontSize=26,
subtitleFontSize=16,
subtitleColor="#666666",
anchor="start",
offset=16,
),
padding={"left": 20, "right": 20, "top": 20, "bottom": 20},
)
.configure_axis(grid=False)
.configure_view(strokeWidth=0)
)

# Save
chart.save("plot.png", scale_factor=3.0)
# Save — target: 3600×3600 square format
chart.save("plot.png", scale_factor=3.6)
chart.save("plot.html")
Loading