Woodshop
Search…
Create multiple line charts
This example shows you how to create a multiple-line chart.

Example of expected JSON Format

1
{
2
labels: ['W48-2020', 'W49-2020', ...],
3
values: [
4
{ key: 'orders', values: ['2', '3', ...] },
5
{ key: 'new_users', values: ['0', '0', ...] },
6
...
7
]
8
}
Copied!
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.
1
const _ = require('lodash');
2
const moment = require('moment');
3
4
const express = require('express');
5
const router = express.Router();
6
7
const Liana = require('forest-express-sequelize');
8
const models = require('../models');
9
10
11
router.post('/stats/multilines', (request, response, next) => {
12
/* Here the query with the 2 lines: orders & new_users */
13
const query = `
14
select 'orders' as "key", week_day, nb from week_orders
15
union
16
select 'new_users' as "key", week_day, nb from week_new_users
17
order by week_day, "key"
18
`;
19
20
return models.sequelize
21
.query(query)
22
.then((results) => {
23
const records = results[0];
24
25
/* Expected Result:
26
labels (X-axis),
27
[values] (Y-axis): one array per line */
28
let resultsFormated = { labels: [], values: [] };
29
30
/* Get the X-axis labels => Week numbers */
31
const weeks = _.uniq(records.map((r) => r.week_day ));
32
resultsFormated.labels = weeks.map((m) => moment(m).format('[W]w-YYYY'));
33
34
/* Get the Y-axis values */
35
var keys = _.uniq(records.map((r) => r.key));
36
37
/* Build one array per key / line */
38
keys.forEach((key) => {
39
var current = _.filter(records, { key });
40
const values = current.map((c) => c.nb);
41
42
resultsFormated.values.push({
43
key: key,
44
values: values
45
});
46
});
47
48
/* Use Liana.StatSerializer to Jsonify the result */
49
var json = new Liana.StatSerializer({ value: resultsFormated }).perform();
50
response.send(json);
51
52
});
53
});
Copied!
Last modified 8mo ago