Create multiple line charts

This example shows you how to create a multiple-line chart.

Example of expected JSON Format

{
  labels: ['W48-2020', 'W49-2020', ...], 
  values: [
    { key: 'orders', values: ['2', '3', ...] }, 
    { key: 'new_users', values: ['0', '0', ...] }, 
    ...
  ] 
} 

The JSON is composed of

  • labels for the X-Axis

  • values for the Y-Axis. values is an array, each item is a line of the chart. A line is a key/values object with key for the line's name.

How to build the expected JSON for multiple-line chart

The following example uses a raw SQL query but it could be replaced by a Sequelize / Mongoose query.

const _ = require('lodash');
const moment = require('moment');

const express = require('express');
const router = express.Router();

const Liana = require('forest-express-sequelize');
const models = require('../models');


router.post('/stats/multilines', (request, response, next) => {
  /* Here the query with the 2 lines: orders & new_users */
  const query = `
    select 'orders' as "key", week_day, nb from week_orders 
    union 
    select 'new_users' as "key", week_day, nb from week_new_users  
    order by week_day, "key"
  `;

  return models.sequelize
    .query(query)
    .then((results) => {
      const records = results[0];

      /* Expected Result: 
          labels (X-axis),
          [values] (Y-axis): one array per line */
      let resultsFormated = { labels: [], values: [] };

      /* Get the X-axis labels => Week numbers */
      const weeks = _.uniq(records.map((r) => r.week_day ));
      resultsFormated.labels = weeks.map((m) => moment(m).format('[W]w-YYYY'));

      /* Get the Y-axis values */
      var keys = _.uniq(records.map((r) => r.key));

      /* Build one array per key / line */
      keys.forEach((key) => {
        var current = _.filter(records, { key });
        const values = current.map((c) => c.nb);

        resultsFormated.values.push({
          key: key,
          values: values
        });
      });

      /* Use Liana.StatSerializer to Jsonify the result */
      var json = new Liana.StatSerializer({ value: resultsFormated }).perform();
      response.send(json);
      
    });
});

Last updated