{"spec_id":"dashboard-metrics-tiles","library":"plotnine","language":"python","code":"\"\"\" anyplot.ai\ndashboard-metrics-tiles: Real-Time Dashboard Tiles\nLibrary: plotnine 0.15.4 | Python 3.13.13\nQuality: 86/100 | Updated: 2026-05-21\n\"\"\"\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom plotnine import (\n    aes,\n    element_blank,\n    element_rect,\n    element_text,\n    facet_wrap,\n    geom_line,\n    geom_rect,\n    geom_text,\n    ggplot,\n    labs,\n    scale_color_identity,\n    scale_x_continuous,\n    scale_y_continuous,\n    theme,\n    theme_void,\n)\n\n\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nELEVATED_BG = \"#FFFDF6\" if THEME == \"light\" else \"#242420\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\nSPARKLINE_BG = \"#EDEAE0\" if THEME == \"light\" else \"#2A2A26\"\n\n# imprint semantic anchors\nSTATUS_COLORS = {\n    \"good\": \"#009E73\",  # green\n    \"warning\": \"#DDCC77\",  # amber\n    \"critical\": \"#AE3030\",  # red\n}\n\nnp.random.seed(42)\n\nmetrics = [\n    {\"name\": \"CPU Usage\", \"value\": 45, \"unit\": \"%\", \"change\": -5.2, \"status\": \"good\"},\n    {\"name\": \"Memory\", \"value\": 72, \"unit\": \"%\", \"change\": 8.3, \"status\": \"warning\"},\n    {\"name\": \"Response Time\", \"value\": 120, \"unit\": \"ms\", \"change\": -15.4, \"status\": \"good\"},\n    {\"name\": \"Active Users\", \"value\": 1284, \"unit\": \"\", \"change\": 12.7, \"status\": \"good\"},\n    {\"name\": \"Error Rate\", \"value\": 0.8, \"unit\": \"%\", \"change\": 45.2, \"status\": \"critical\"},\n    {\"name\": \"Throughput\", \"value\": 3450, \"unit\": \"req/s\", \"change\": -2.1, \"status\": \"good\"},\n]\n\n# Generate sparkline history for each metric\nn_points = 20\nsparkline_data = []\nfor metric in metrics:\n    base_value = metric[\"value\"]\n    trend_direction = -1 if metric[\"change\"] < 0 else 1\n    noise = np.random.randn(n_points) * (base_value * 0.1)\n    trend = np.linspace(0, trend_direction * abs(metric[\"change\"]) / 100 * base_value, n_points)\n    history = base_value - trend + noise\n\n    hist_min, hist_max = history.min(), history.max()\n    history_norm = (history - hist_min) / (hist_max - hist_min) if hist_max > hist_min else np.ones(n_points) * 0.5\n    history_scaled = history_norm * 0.22 + 0.03\n\n    for j, val in enumerate(history_scaled):\n        sparkline_data.append(\n            {\n                \"metric_name\": metric[\"name\"],\n                \"x\": j / (n_points - 1) * 18 + 1,\n                \"y\": val,\n                \"line_color\": STATUS_COLORS[metric[\"status\"]],\n            }\n        )\n\ndf_sparkline = pd.DataFrame(sparkline_data)\n\n# Build label rows with theme-adaptive and status-aware colors\nlabel_data = []\nfor metric in metrics:\n    value = metric[\"value\"]\n    value_str = f\"{value:,.0f}\" if value >= 1000 else (f\"{value:.1f}\" if value < 1 else f\"{value:.0f}\")\n    value_display = f\"{value_str}{metric['unit']}\"\n\n    change = metric[\"change\"]\n    arrow = \"▲\" if change >= 0 else \"▼\"\n    change_str = f\"{arrow} {abs(change):.1f}%\"\n\n    # Context-aware change color: for error rate, up = bad\n    if metric[\"name\"] == \"Error Rate\":\n        change_color = \"#C475FD\" if change >= 0 else \"#009E73\"\n    else:\n        change_color = \"#009E73\" if change >= 0 else \"#C475FD\"\n\n    label_data.append(\n        {\n            \"metric_name\": metric[\"name\"],\n            \"metric_label\": metric[\"name\"],\n            \"value_display\": value_display,\n            \"change_str\": change_str,\n            \"status_color\": STATUS_COLORS[metric[\"status\"]],\n            \"change_color\": change_color,\n            \"ink_color\": INK,\n            \"label_x\": 10,\n            \"label_y\": 0.88,\n            \"value_x\": 10,\n            \"value_y\": 0.62,\n            \"change_x\": 10,\n            \"change_y\": 0.38,\n        }\n    )\n\ndf_labels = pd.DataFrame(label_data)\n\nall_metrics = [m[\"name\"] for m in metrics]\ndf_sparkline[\"metric_name\"] = pd.Categorical(df_sparkline[\"metric_name\"], categories=all_metrics, ordered=True)\ndf_labels[\"metric_name\"] = pd.Categorical(df_labels[\"metric_name\"], categories=all_metrics, ordered=True)\n\nbg_data = [{\"metric_name\": m[\"name\"], \"xmin\": 0, \"xmax\": 20, \"ymin\": 0, \"ymax\": 0.28} for m in metrics]\ndf_bg = pd.DataFrame(bg_data)\ndf_bg[\"metric_name\"] = pd.Categorical(df_bg[\"metric_name\"], categories=all_metrics, ordered=True)\n\n# Plot\nplot = (\n    ggplot()\n    # Sparkline area background\n    + geom_rect(df_bg, aes(xmin=\"xmin\", xmax=\"xmax\", ymin=\"ymin\", ymax=\"ymax\"), fill=SPARKLINE_BG)\n    # Sparklines — thicker for visibility, colored by status\n    + geom_line(df_sparkline, aes(x=\"x\", y=\"y\", color=\"line_color\"), size=1.4, alpha=0.9)\n    # Metric label\n    + geom_text(\n        df_labels,\n        aes(x=\"label_x\", y=\"label_y\", label=\"metric_label\", color=\"ink_color\"),\n        size=7,\n        ha=\"center\",\n        va=\"center\",\n        fontweight=\"bold\",\n    )\n    # Main value (colored by status)\n    + geom_text(\n        df_labels,\n        aes(x=\"value_x\", y=\"value_y\", label=\"value_display\", color=\"status_color\"),\n        size=13,\n        ha=\"center\",\n        va=\"center\",\n        fontweight=\"bold\",\n    )\n    # Change indicator (colored green/red by favorable/unfavorable direction)\n    + geom_text(\n        df_labels,\n        aes(x=\"change_x\", y=\"change_y\", label=\"change_str\", color=\"change_color\"),\n        size=6,\n        ha=\"center\",\n        va=\"center\",\n    )\n    # Use hex values directly from data columns\n    + scale_color_identity()\n    + facet_wrap(\"~metric_name\", ncol=3)\n    + scale_x_continuous(limits=(0, 20), expand=(0.02, 0.02))\n    + scale_y_continuous(limits=(0, 1), expand=(0.02, 0.02))\n    + labs(title=\"dashboard-metrics-tiles · python · plotnine · anyplot.ai\")\n    + theme_void()\n    + theme(\n        figure_size=(8, 4.5),\n        plot_title=element_text(size=10, ha=\"center\", color=INK, margin={\"b\": 12}),\n        strip_text=element_blank(),\n        strip_background=element_blank(),\n        panel_spacing=0.12,\n        panel_background=element_rect(fill=ELEVATED_BG, color=INK_SOFT, size=0.5),\n        plot_background=element_rect(fill=PAGE_BG, color=PAGE_BG),\n        legend_position=\"none\",\n    )\n)\n\nplot.save(f\"plot-{THEME}.png\", dpi=400, width=8, height=4.5, units=\"in\", verbose=False)\n"}