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
132 changes: 93 additions & 39 deletions plots/slope-basic/implementations/python/altair.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,14 @@
""" anyplot.ai
slope-basic: Basic Slope Chart (Slopegraph)
Library: altair 6.1.0 | Python 3.13.13
Quality: 86/100 | Created: 2026-04-30
Library: altair 6.2.2 | Python 3.13.14
Quality: 87/100 | Created: 2026-07-25
"""

import os
import sys

import altair as alt
import pandas as pd


_script_dir = os.path.dirname(os.path.abspath(__file__))
if _script_dir in sys.path:
sys.path.remove(_script_dir)

import altair as alt # noqa: E402
from PIL import Image


# Theme tokens
Expand All @@ -24,27 +18,28 @@
INK = "#1A1A17" if THEME == "light" else "#F0EFE8"
INK_SOFT = "#4A4A44" if THEME == "light" else "#B8B7B0"

# Okabe-Ito: position 1 = Increase, position 2 = Decrease
# Imprint palette: position 1 = Increase, position 5 (deferred semantic-red anchor) = Decrease
COLOR_INCREASE = "#009E73"
COLOR_DECREASE = "#AE3030" # imprint red — decrease
COLOR_DECREASE = "#AE3030"

# Data
# Data — Q1 vs Q4 product sales, deliberately spaced (min gap ~90 units within each
# period) so entity labels never crowd, with a full rank shuffle for a rich story
data = pd.DataFrame(
{
"Product": [
"Laptop",
"Phone",
"Tablet",
"Monitor",
"Keyboard",
"Mouse",
"Headphones",
"Webcam",
"Speaker",
"Charger",
"Monitor",
"Headphones",
"Keyboard",
"Tablet",
"Mouse",
"Laptop",
"Phone",
],
"Q1 Sales": [850, 1200, 420, 310, 580, 720, 390, 180, 260, 440],
"Q4 Sales": [920, 980, 650, 410, 520, 810, 620, 350, 240, 380],
"Q1 Sales": [190, 310, 400, 490, 580, 680, 780, 890, 1010, 1150],
"Q4 Sales": [400, 190, 310, 580, 780, 490, 890, 680, 1150, 1010],
}
)

Expand All @@ -54,61 +49,120 @@

color_scale = alt.Scale(domain=["Increase", "Decrease"], range=[COLOR_INCREASE, COLOR_DECREASE])

# Title (42 chars < 67 baseline — no fontsize reduction needed)
title = "slope-basic · python · altair · anyplot.ai"
title_fontsize = 16

# Matte-red "Decrease" measures ~2.7:1 against #1A1A17 (below the 3:1 AA floor for
# meaningful status info); per the style guide's stroke recommendation, outline
# Decrease elements with a 1px ink halo in dark mode only (fine on the light bg).
decrease_stroke_width = alt.condition(
alt.datum.Direction == "Decrease", alt.value(1 if THEME == "dark" else 0), alt.value(0)
)

# Plot
lines = (
alt.Chart(df_long)
.mark_line(strokeWidth=3, opacity=0.8)
.encode(
x=alt.X("Period:N", axis=alt.Axis(labelFontSize=20, title=None, labelAngle=0)),
x=alt.X("Period:N", axis=alt.Axis(labelFontSize=11, title=None, labelAngle=0)),
y=alt.Y(
"Sales:Q",
axis=alt.Axis(labelFontSize=18, titleFontSize=22, title="Sales (units)"),
axis=alt.Axis(labelFontSize=10, titleFontSize=12, title="Sales (units)"),
scale=alt.Scale(zero=False),
),
color=alt.Color(
"Direction:N", scale=color_scale, legend=alt.Legend(titleFontSize=20, labelFontSize=18, orient="top-right")
"Direction:N", scale=color_scale, legend=alt.Legend(titleFontSize=12, labelFontSize=10, orient="top-right")
),
detail="Product:N",
)
)

lines_decrease_halo = (
alt.Chart(df_long[df_long["Direction"] == "Decrease"])
.mark_line(strokeWidth=5, opacity=0.9, color=INK)
.encode(x="Period:N", y="Sales:Q", detail="Product:N")
)

points = (
alt.Chart(df_long)
.mark_circle(size=200, opacity=0.9)
.encode(x="Period:N", y="Sales:Q", color=alt.Color("Direction:N", scale=color_scale, legend=None))
.encode(
x="Period:N",
y="Sales:Q",
color=alt.Color("Direction:N", scale=color_scale, legend=None),
stroke=alt.value(INK),
strokeWidth=decrease_stroke_width,
)
)

labels_left = (
alt.Chart(df_long[df_long["Period"] == "Q1 Sales"])
.mark_text(align="right", dx=-15, fontSize=16)
.encode(x="Period:N", y="Sales:Q", text="Product:N", color=alt.Color("Direction:N", scale=color_scale, legend=None))
.mark_text(align="right", dx=-12, fontSize=11)
.encode(
x="Period:N",
y="Sales:Q",
text="Product:N",
color=alt.Color("Direction:N", scale=color_scale, legend=None),
stroke=alt.value(INK),
strokeWidth=decrease_stroke_width,
)
)

labels_right = (
alt.Chart(df_long[df_long["Period"] == "Q4 Sales"])
.mark_text(align="left", dx=15, fontSize=16)
.encode(x="Period:N", y="Sales:Q", text="Product:N", color=alt.Color("Direction:N", scale=color_scale, legend=None))
.mark_text(align="left", dx=12, fontSize=11)
.encode(
x="Period:N",
y="Sales:Q",
text="Product:N",
color=alt.Color("Direction:N", scale=color_scale, legend=None),
stroke=alt.value(INK),
strokeWidth=decrease_stroke_width,
)
)

# Style
# Layer order: dark-mode Decrease halo sits beneath everything else; empty in light mode.
layers = [lines_decrease_halo] if THEME == "dark" else []
layers += [lines, points, labels_left, labels_right]

# Style — L-shaped frame: no view stroke, axis domain lines (bottom + left) stay visible
chart = (
(lines + points + labels_left + labels_right)
.properties(width=1400, height=850, background=PAGE_BG, title="slope-basic · altair · anyplot.ai")
.configure_title(color=INK, fontSize=28, anchor="middle")
alt.layer(*layers)
.properties(
width=620,
height=320,
background=PAGE_BG,
title=alt.Title(title, fontSize=title_fontsize, color=INK, anchor="middle"),
)
.configure_view(fill=PAGE_BG, strokeWidth=0)
.configure_axis(
domainColor=INK_SOFT,
tickColor=INK_SOFT,
grid=True,
gridColor=INK,
gridOpacity=0.10,
gridDash=[4, 4],
gridOpacity=0.12,
labelColor=INK_SOFT,
titleColor=INK,
)
.configure_view(fill=PAGE_BG, stroke=INK_SOFT)
.configure_legend(fillColor=ELEVATED_BG, strokeColor=INK_SOFT, labelColor=INK_SOFT, titleColor=INK)
)

# Save
chart.save(f"plot-{THEME}.png", scale_factor=3.0)
# Save PNG then pad to exact 3200×1800 target
chart.save(f"plot-{THEME}.png", scale_factor=4.0)

TW, TH = 3200, 1800
_img = Image.open(f"plot-{THEME}.png").convert("RGB")
_w, _h = _img.size
if _w > TW or _h > TH:
raise SystemExit(
f"altair vl-convert produced {_w}×{_h}, exceeds target {TW}×{TH}. "
f"Shrink chart .properties(width=, height=) values and re-render."
)
if _w < TW or _h < TH:
_canvas = Image.new("RGB", (TW, TH), PAGE_BG)
_canvas.paste(_img, ((TW - _w) // 2, (TH - _h) // 2))
_canvas.save(f"plot-{THEME}.png")

# Save interactive HTML
chart.save(f"plot-{THEME}.html")
Loading
Loading