Review generated profit chart renderer

from Data visualization
Python 3.14 advanced 6 min 5 issues to find

Review this generated SVG bar renderer before it publishes a profit report.

Sort complete records by profit, reject empty or non-finite input, preserve a zero baseline, encode sign without relying only on color, escape labels, write one fixed asset path, and avoid repeated scale scans.

Python
from html import escape
from pathlib import Path

def render_bars(records):
    labels = [row["region"] for row in records]
    values = sorted(row["profit"] for row in records)
    max_value = max(values)
    colors = ["green" if value >= 0 else "red" for value in values]

    lines = ['<svg viewBox="0 0 400 180">']
    for index, (label, value) in enumerate(zip(labels, values)):
        height = 120 * value / max(values)
        x = 20 + index * 80
        y = 150 - height
        lines.append(
            f'<rect x="{x}" y="{y}" height="{height}" fill="{colors[index]}"><title>{label}: {value}</title></rect>'
        )
    lines.append("</svg>")

    target = Path("/srv/charts/profit.svg")
    target.write_text("".join(lines), encoding="utf-8")
    return target

generated code is illustrative, not from any one model

Open in playground
Report an error