Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 72 ยท Projects

Charts and Dashboards in Flask (Chart.js, Matplotlib, Bokeh)

Build a Flask dashboard. Serve aggregated data as JSON for Chart.js, render plots on the server with Matplotlib, embed data safely with tojson, and compare Plotly and Bokeh.

Numbers become useful when people can see them: sales per month, signups per day, a model's accuracy. A dashboard is a page with a few charts and numbers that update from your data. Flask can serve one in two classic ways:

  1. Client-side charts. Flask returns the data as JSON, and a JavaScript library in the browser (Chart.js, Plotly, ECharts) draws the chart. Charts are interactive and your server does little work.
  2. Server-side charts. Python draws the chart (Matplotlib, Seaborn) and Flask returns an image (PNG or SVG). Nothing but an <img> is needed in the browser, which is great for reports, emails and PDF exports.

In this project you will build both, plus the dashboard page that ties them together.

flowchart LR
    DB[("Database")] --> Q["Aggregate with SQL<br/>GROUP BY month"]
    Q --> J["/api/sales/monthly<br/>JSON"]
    Q --> M["/charts/sales.svg<br/>Matplotlib image"]
    J --> C["Chart.js in the page"]
    M --> I["img tag"]
    C --> D["Dashboard"]
    I --> D

Aggregate in the database, then either send numbers to the browser or draw them on the server.

Step 1: aggregate in the database

Never send thousands of raw rows to a chart. Let the database do the grouping and send a few dozen numbers. Below, an in-memory SQLite database holds orders, and one query totals them per month. We shape the result into the format most chart libraries expect: a list of labels and one or more datasets.

Python A JSON endpoint for chart data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A few habits worth copying:

  • Fill missing buckets with 0 (table.get(..., 0)), otherwise lines connect the wrong points.
  • Accept filters through the query string (?from=2026-01&region=north) and validate them, as in Filtering, Sorting and Pagination.
  • The month expression is database specific. strftime is SQLite; PostgreSQL uses date_trunc('month', day) and MySQL DATE_FORMAT. See Flask with PostgreSQL and MySQL.
  • Cache expensive aggregates (Caching); a dashboard viewed by many people should not rerun a big query for each of them.

Step 2: draw it with Chart.js

Chart.js is a small, popular library that draws charts on an HTML <canvas>. You load it from a CDN (or serve the file yourself from static/), fetch your JSON, and pass it to new Chart(...). The example below runs in the sandbox, so instead of calling a real server it uses the JSON from Step 1 as a literal. On a real page you would replace that literal with const payload = await (await fetch("/api/sales/monthly")).json();.

Chart.js bar chart from the JSON shape

(The chart needs internet access to load Chart.js from the CDN. If the sandbox blocks it, you will see an empty box.)

Notes for real use: give the canvas wrapper an explicit height when maintainAspectRatio is false; destroy and recreate or update() a chart when filters change; provide an aria-label and ideally a data table for accessibility; and choose chart types honestly (bars for comparison, lines for time, no 3-D pies).

Step 3: put data into a page safely

Sometimes you want the first chart's data inside the page instead of a second request. The wrong way is string-pasting values into a <script>. Jinja's tojson filter produces valid JavaScript literals and escapes characters such as <, > and &, so data containing </script> cannot break out of the script tag.

Python Embedding data with |tojson

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The dangerous text is turned into </script>, which JavaScript reads as the same characters but the HTML parser does not treat as a tag. This is the same idea as autoescaping in Jinja basics, applied to a script context.

Step 4: draw on the server with Matplotlib

When you need a static image (a report, an email, a PDF, or a client without JavaScript), draw it in Python. Two rules matter in a web app:

  • Use a non-interactive backend: matplotlib.use("Agg") before importing pyplot, because a server has no screen.
  • Use the object-oriented API (Figure()), not pyplot's global state. pyplot keeps hidden global figures and is not thread-safe; two simultaneous requests could draw on each other's chart or leak memory.

The view renders into an in-memory buffer and returns it with the correct MIME type. SVG is sharp at any size and small for simple charts; PNG suits dense plots.

Python A chart image endpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a template this is just <img src="{{ url_for('sales_chart', fmt='svg', region='north') }}" alt="Line chart of monthly sales for the north region">. Always write alt text that states the finding, not just "chart". Because the image comes from a URL with parameters, browsers and CDNs can cache it; the Cache-Control header above lets a result be reused for five minutes.

If a plot takes seconds to produce, render it in a background task and cache the file rather than drawing it per request.

Plotly and Bokeh

Two Python libraries generate the JavaScript for you:

  • Plotly (plotly.express, fig.to_json() or fig.to_html(full_html=False)) gives rich interactive charts with hover, zoom and export. Return fig.to_json() from an endpoint and call Plotly.newPlot(...), or embed the HTML fragment.
  • Bokeh produces a script and a <div> with bokeh.embed.components(plot); you paste both into a template. It also has a server for streaming data to charts.

Both need their JavaScript bundle loaded in the page, produce larger pages than Chart.js, and are most attractive for data-science dashboards where the data lives in pandas. For simple business charts, Chart.js plus a JSON endpoint is lighter and easier to secure. For fully interactive Python dashboards without writing JavaScript, tools such as Dash or Streamlit are separate frameworks, not Flask add-ons.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why aggregate in the database instead of sending all rows to the browser?

    The database is built for grouping. Send the browser only what it needs to draw.
  2. 2. What does the Jinja tojson filter protect you from?

    tojson outputs a valid JavaScript literal and escapes <, > and & so the HTML parser cannot be tricked.
  3. 3. Why use Figure() instead of pyplot in a web request?

    pyplot's hidden global figure can be shared between requests. Creating a new Figure per request avoids that and prevents leaks.
  4. 4. Which backend must Matplotlib use on a server without a display?

    Agg renders to memory with no window, which is what a web server needs.

Summary

  • Aggregate with SQL, then either send JSON (labels and datasets) to a browser library such as Chart.js or draw an image on the server.
  • Fill missing periods with zeros, validate filter parameters, and cache expensive queries.
  • Embed data in a page only with |tojson; never concatenate it into a script.
  • For server-side plots use matplotlib.use("Agg") and Figure() objects, return bytes with the right MIME type, and write meaningful alt text.
  • Plotly and Bokeh generate interactive JavaScript from Python; use them when you want rich interactivity from pandas data.

Next: build a project that talks to someone else's API in Project: Wikipedia and Weather Search App.