#!/usr/bin/env python3
"""Draw the article's charts as static inline SVG from derived/results.json.
Run after analyze.py: python3 -I analysis/heat/charts.py
Writes guides-src/tools/heat-style.html and guides-src/tools/heat-chart-*.html.
Each chart is drawn twice, 340 and 680 units wide, and CSS shows the one that fits, so type stays legible on a phone.
Standard library only.
"""
import json, os
HERE = os.path.dirname(os.path.abspath(__file__))
TOOLS = os.path.join(HERE, '..', '..', 'guides-src', 'tools')
R = json.load(open(os.path.join(HERE, 'derived', 'results.json')))
ACCENT, LIGHT = '#B4532A', '#D99A7C' # one hue, two steps; checked with the dataviz palette validator on #FBF5EC
SIZES = (('n', 340), ('w', 680))
def n(x):
return f'{round(x):,}'
def esc(s):
return str(s).replace('&', '&').replace('<', '<')
def svg(cls, w, h, body, label):
return f''
def bar_h(x, y, w, h, fill, title):
"""Horizontal bar: square at the baseline (left), 4px rounded data end."""
w = max(w, 0.5); r = min(4, w / 2, h / 2)
return (f''
f'{esc(title)}')
def bar_v(x, y, w, h, fill, title):
"""Column: square at the baseline, 4px rounded top."""
h = max(h, 0.5); r = min(4, w / 2, h)
return (f''
f'{esc(title)}')
def figure(name, title, sub, svgs, table, note='', legend=''):
head, rows = table
t = ('
' + ''.join(f'
{esc(h)}
' for h in head) + '
' +
''.join('
' + ''.join(f'
{esc(c)}
' for c in r) + '
' for r in rows) + '
')
html = (f'\n
{esc(title)}
\n
{esc(sub)}
\n{legend}' + '\n'.join(svgs) +
(f'\n
{esc(note)}
' if note else '') +
f'\nShow the numbers{t}\n\n')
with open(os.path.join(TOOLS, name + '.html'), 'w') as f:
f.write(html)
print('wrote', name, len(html), 'bytes')
# ------------------------------------------------------------------ shared style
STYLE = """
"""
with open(os.path.join(TOOLS, 'heat-style.html'), 'w') as f:
f.write(STYLE)
# ------------------------------------------------------------------ 1. persistence
P = R['persistence_counts_last4']
NAMES = {'0': 'None', '1': '1', '2-4': '2 to 4', '5-9': '5 to 9', '10-24': '10 to 24', '25-49': '25 to 49', '50+': '50 or more'}
svgs = []
for cls, W in SIZES:
left, right, rowh, top = (72, 44, 44, 26) if W < 500 else (96, 56, 44, 26)
pw = W - left - right
H = top + rowh * len(P) + 24
b = f'Complaints in one winter'
for q in (0, 25, 50, 75, 100):
x = left + pw * q / 100
b += f''
b += f'{q}%'
for i, r in enumerate(reversed(P)):
y = top + i * rowh + 6
b += f'{NAMES[r["band"]]}'
wa, wt = pw * r['any_next'] / 100, pw * r['ge10_next'] / 100
b += bar_h(left, y, wa, 13, LIGHT, f'{NAMES[r["band"]]} last winter: {r["any_next"]}% had at least one complaint the next winter')
b += bar_h(left, y + 15, wt, 13, ACCENT, f'{NAMES[r["band"]]} last winter: {r["ge10_next"]}% had 10 or more the next winter')
# value labels sit past the bar end; the two never share a line
b += f'{r["any_next"]:.0f}%'
lab = f'{r["ge10_next"]:.0f}%' if r['ge10_next'] >= 1 else f'{r["ge10_next"]}%'
b += f'{lab}'
svgs.append(svg(cls, W, H, b, 'Bar chart: share of buildings that had any complaint, and 10 or more complaints, the following winter, by how many they had the winter before.'))
legend = f'
Any complaint the next winter10 or more the next winter
\n'
figure('heat-chart-next-winter', 'What one winter says about the next',
'Buildings with three or more apartments, grouped by heat and hot water complaints in one winter. Bars show what share went on to complain the following winter. Four pairs of winters, 2021-22 through 2025-26.',
svgs, (['Complaints one winter', 'Buildings per winter', 'Any the next winter', '10 or more the next', 'Range across the four pairs (10 or more)'],
[[NAMES[r['band']], n(r['lots_per_pair']), f'{r["any_next"]}%', f'{r["ge10_next"]}%', f'{r["min_ge10"]}% to {r["max_ge10"]}%'] for r in reversed(P)]),
legend=legend)
# ------------------------------------------------------------------ 2. temperature
S = R['scatter']; B5 = R['by_low_5']; big = R['biggest_days'][0]
svgs = []
for cls, W in SIZES:
left, right, top, H = (38, 10, 16, 300) if W < 500 else (46, 16, 16, 380)
bottom = 36
pw, ph = W - left - right, H - top - bottom
X = lambda t: left + pw * (t - 0) / 72
Y = lambda c: top + ph * (1 - c / 6400)
b = ''
for c in (0, 2000, 4000, 6000):
b += f'{n(c)}'
for t in range(10, 71, 10):
b += f'{t}°'
b += f'Lowest temperature that day in Central Park (°F)'
# every day is one dot; split across layers so overlapping days read darker
rad = 2.4 if W < 500 else 3
layers = [[] for _ in range(6)]
for i, (t, c, m) in enumerate(S):
jit = ((i * 37) % 9 - 4) / 9 * 0.8 # spread whole-degree lows a little so columns of dots do not stack
layers[i % 6].append(f'M{X(t + jit):.0f} {Y(min(c, 6400)):.0f}h.01')
for L in layers:
b += f''
pts = [(X(r['low'] + 2.5), Y(r['median'])) for r in B5]
b += f''
b += f''
for (x, y), r in zip(pts, B5):
lab = 'under 10' if r['low'] == 5 else '65 and up' if r['low'] == 65 else f'{r["low"]} to {r["low"] + 4}'
b += f'Lows {lab}°F: median {n(r["median"])} complaints a day over {r["days"]} days'
# direct labels: the two ends of the median line and the single biggest day
x0, y0 = pts[0]; x1, y1 = pts[-1]
b += f'{n(B5[0]["median"])} a day'
b += f'{n(B5[-1]["median"])}'
bx, by = X(big['low']), Y(big['complaints'])
b += f''
b += f'Feb 8, 2026: {n(big["complaints"])}'
svgs.append(svg(cls, W, H, b, 'Scatter plot: heat complaints per day against the daily low temperature, with the median for each five-degree band.'))
legend = f'
One dayMedian day for each 5° band
\n'
figure('heat-chart-temperature', 'Complaints per day against the daily low',
f'Every day of ten heat seasons, October 2016 through May 2026: {n(len(S))} days.',
svgs, (['Daily low (°F)', 'Days', 'Median complaints a day', 'Middle half of days'],
[['under 10' if r['low'] == 5 else '65 and up' if r['low'] == 65 else f'{r["low"]} to {r["low"] + 4}', r['days'], n(r['median']), f'{n(r["q1"])} to {n(r["q3"])}'] for r in B5]),
legend=legend)
# ------------------------------------------------------------------ 3. first cold days
O = R['cold_day_order']
LAB = {'1-3': ('1st to 3rd', '1–3'), '4-10': ('4th to 10th', '4–10'), '11-20': ('11th to 20th', '11–20'), '21-40': ('21st to 40th', '21–40'), '41+': ('41st and later', '41+')}
svgs = []
for cls, W in SIZES:
left, right, top, H = (38, 8, 20, 250) if W < 500 else (46, 150, 20, 280)
bottom = 40
pw, ph = W - left - right, H - top - bottom
Y = lambda c: top + ph * (1 - c / 2400)
b = ''
for c in (0, 500, 1000, 1500, 2000):
b += f'{n(c)}'
slot = pw / len(O)
for i, r in enumerate(O):
cx = left + slot * (i + .5)
b += bar_v(cx - 12, Y(r['median']), 24, Y(0) - Y(r['median']), ACCENT if i == 0 else LIGHT,
f'{LAB[r["nth_cold_day"]][0]} cold day of the season: median {n(r["median"])} complaints, {r["days"]} days')
b += f'{n(r["median"])}'
b += f'{LAB[r["nth_cold_day"]][1]}'
b += f'Cold days so far that season'
svgs.append(svg(cls, W, H, b, 'Column chart: median complaints on days with lows of 35 to 44 degrees, by how many cold days the season had already had.'))
figure('heat-chart-first-cold', 'The same cold draws three times the complaints early in the season',
'Median complaints on days with a low of 35 to 44°F, by how many days with a low under 45°F the season had already had. Ten seasons.',
svgs, (['Cold day of the season', 'Days', 'Median complaints', 'Middle half of days', 'Against the same winter’s Dec to Feb median'],
[[LAB[r['nth_cold_day']][0], r['days'], n(r['median']), f'{n(r["q1"])} to {n(r["q3"])}', f'{r["median_ratio_to_own_midwinter"]}×'] for r in O]))
# ------------------------------------------------------------------ 4. ten winters
WN = R['winters']
svgs = []
for cls, W in SIZES:
left, right = (38, 6) if W < 500 else (46, 120)
pw = W - left - right
panel = 120
H = 34 + panel + 56 + panel + 30
slot = pw / len(WN); bw = 16 if W < 500 else 22
b = ''
for k, (key, title, ymax, ticks) in enumerate((('per_hdd', 'Complaints per heating degree day', 80, (0, 40, 80)), ('hdd', 'Heating degree days, October through May', 5000, (0, 2500, 5000)))):
top = 34 + k * (panel + 56)
Y = lambda c: top + panel * (1 - c / ymax)
b += f'{title}'
for c in ticks:
b += f'{n(c)}'
vals = [r[key] for r in WN]
for i, r in enumerate(WN):
cx = left + slot * (i + .5); v = r[key]
wl = f'{r["winter"]}-{str(r["winter"] + 1)[2:]}'
b += bar_v(cx - bw / 2, Y(v), bw, Y(0) - Y(v), ACCENT if i == len(WN) - 1 else LIGHT,
f'{wl}: {n(r["complaints"])} complaints, {n(r["hdd"])} degree days, {r["per_hdd"]} complaints per degree day')
if i in (0, len(WN) - 1) or v == min(vals): # label the ends and the low point only
b += f'{v if key == "per_hdd" else n(v)}'
for i, r in enumerate(WN):
cx = left + slot * (i + .5)
b += f'’{str(r["winter"])[2:]}'
b += f'Winter starting in October of each year'
svgs.append(svg(cls, W, H, b, 'Two column charts over ten winters: complaints per heating degree day, and heating degree days.'))
figure('heat-chart-winters', 'Last winter was the coldest of the ten, and complaints rose faster than the cold',
'A heating degree day is one degree of daily average temperature below 65°F. Central Park, October 1 through May 31.',
svgs, (['Winter', 'Complaints', 'Buildings', 'Degree days', 'Complaints per degree day', 'Days with a freezing low'],
[[f'{r["winter"]}-{str(r["winter"] + 1)[2:]}', n(r['complaints']), n(r['lots']), n(r['hdd']), r['per_hdd'], r['days_low_le_32']] for r in WN]))
# ------------------------------------------------------------------ 5. age
A = R['by_age']
ALAB = {'before 1900': 'Before 1900', '1900-19': '1900 to 1919', '1920-39': '1920 to 1939', '1940-59': '1940 to 1959', '1960-79': '1960 to 1979', '1980-99': '1980 to 1999', '2000-09': '2000 to 2009', '2010 on': '2010 and later'}
svgs = []
for cls, W in SIZES:
left, right, rowh, top = (96, 36, 26, 22) if W < 500 else (110, 200, 28, 22)
pw = W - left - right
H = top + rowh * len(A) + 4
b = ''
for q in (0, 10, 20):
x = left + pw * q / 24
b += f''
b += f'{q}'
for i, r in enumerate(A):
y = top + i * rowh + 4; v = r['per_100_apartments_excl_condo_coop']
b += f'{ALAB[r["built"]]}'
b += bar_h(left, y, pw * v / 24, 14, ACCENT, f'Built {ALAB[r["built"]].lower()}: {v} complaints per 100 apartments last winter')
b += f'{v}'
svgs.append(svg(cls, W, H, b, 'Bar chart: heat complaints per 100 apartments last winter by the year the building was built.'))
figure('heat-chart-age', 'Complaints per 100 apartments, by when the building went up',
'Winter 2025-26. Buildings with three or more apartments, leaving out condos and co-ops.',
svgs, (['Built', 'Buildings', 'Apartments', 'Complaints per 100 apartments', 'Same, with condos and co-ops included'],
[[ALAB[r['built']], n(r['lots_excl']), n(r['units_excl']), r['per_100_apartments_excl_condo_coop'], r['per_100_apartments']] for r in A]))
# ------------------------------------------------------------------ citywide figures embedded in the address lookup
import re # noqa: E402
WORDS = {'0': 'no complaints', '1': '1 complaint', '2-4': '2 to 4 complaints', '5-9': '5 to 9 complaints', '10-24': '10 to 24 complaints', '25-49': '25 to 49 complaints', '50+': '50 or more complaints'}
RANGE = {'0': (0, 0), '1': (1, 1), '2-4': (2, 4), '5-9': (5, 9), '10-24': (10, 24), '25-49': (25, 49), '50+': (50, 10**9)}
city = {'winter': R['lookup']['winter'],
'bands': {k: {'zero': v['pct_zero'], 'cuts': [[int(q), c] for q, c in sorted(v['rate_cuts'].items(), key=lambda x: int(x[0]))]} for k, v in R['lookup']['bands'].items()},
'next': [{'lo': RANGE[r['band']][0], 'hi': RANGE[r['band']][1], 'words': WORDS[r['band']], 'any': r['any_next'], 'ten': r['ge10_next']} for r in P]}
path = os.path.join(TOOLS, 'heat-lookup.html')
src = open(path).read()
new, k = re.subn(r'/\*DATA\*/.*?/\*END\*/', lambda m: '/*DATA*/' + json.dumps(city, separators=(',', ':')) + '/*END*/', src, flags=re.S)
assert k == 1, 'lookup data marker not found'
open(path, 'w').write(new)
print('updated heat-lookup.html citywide figures')