DEV Community

Cover image for Generating Dynamic SVG Vector Charts from Python Data in a Single Polyglot Script
O-O1112
O-O1112

Posted on

Generating Dynamic SVG Vector Charts from Python Data in a Single Polyglot Script

💡 The Problem: Connecting Backend Data Math to Frontend Vector Graphics

In traditional development, if you want Python to analyze a data series and generate dynamic SVG graphics via Node.js, you have to:

  1. Save the processed numbers to an intermediate JSON file or database.
  2. Spin up an Express / FastAPI endpoint.
  3. Write boilerplate code to parse and map the coordinates.

With Block Engine, you can write native <py> and <js> blocks in a single .blkp document and let variables flow naturally through the in-memory State Pipeline.


💻 Today's Code Snippet: chart_generator.blkp

<py>
# Stage 1: Python calculates statistical trend points
data_points = [15, 28, 42, 65, 80, 95, 110, 140]
max_val = max(data_points)
min_val = min(data_points)
points_count = len(data_points)
print(f"[Python] Prepared {points_count} points. Range: [{min_val}, {max_val}]")
</py>

<js>
// Stage 2: Node.js receives Python variables and computes SVG polygon paths
const width = 500;
const height = 200;
const step = width / (points_count - 1);

const coordinates = data_points.map((val, idx) => {
    const x = idx * step;
    const y = height - ((val - min_val) / (max_val - min_val)) * (height - 30) - 15;
    return `${x},${y}`;
}).join(' ');

console.log("[Node.js] Generated SVG Polyline Coordinates: " + coordinates);
var svg_output = `<svg width="${width}" height="${height}"><polyline fill="none" stroke="#38bdf8" stroke-width="3" points="${coordinates}" /></svg>`;
</js>
Enter fullscreen mode Exit fullscreen mode

âš¡ Running it (Zero-Install):

npx block-engine-runner chart_generator.blkp
Enter fullscreen mode Exit fullscreen mode

Output:

[Python] Prepared 8 points. Range: [15, 140]
[Node.js] Generated SVG Polyline Coordinates: 0,185 71.42,169.4 142.85,152.6 ...
Enter fullscreen mode Exit fullscreen mode

🚀 Key Takeaways

  1. Zero Microservice Overhead: Python handles math and array analysis; Node.js handles string templating and vector math without network sockets.
  2. In-Memory IPC: Data is passed directly across runtime processes without disk I/O bottlenecks.
  3. Single-File Simplicity: The entire pipeline lives in one structured, readable file.

Top comments (0)