审查生成的利润图渲染器

来自 数据可视化
Python 3.14 高级 6分钟 找出 5处问题

在这段生成的 SVG 柱形图渲染器发布利润报告前,对它进行审查。

按利润排序完整记录,拒绝空输入或非有限数值,保留零基线,不只靠颜色编码正负,转义标签,写入固定资源路径,并避免重复扫描尺度。

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

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误