Create a Smart Chart
On the previous page, we learned how API-based charts allow you to fetch any dataset from a custom endpoint. But using the finite list of predefined charts (Single, Distribution, Time-based, etc.), you are still constrained by how that data is displayed. With Smart Charts, you can code exactly what data you want and how you want it displayed!
You need a Starter plan or above to create Smart charts

Creating a Smart Chart

To create a chart and access the Smart Chart Editor, click on the Edit Smart Chart button:
Next, use the Template, Component, and Style tabs to create your customized chart. At any point, you can render your chart by clicking on the Run code button.
Don't forget to click on Create Chart (or Save if the chart is already created) once you're done!
If you are creating a record-specific smart chart (in the record Analytics tab), the record object is directly accessible (either through this.args.record in the component or @record in the template).

Creating a Table Chart

Our first Smart Chart example will be a simple table: however you may choose to make it as complex and customized as you wish.
1
<BetaTable
2
@columns={{array 'Username' 'Points'}}
3
@rows={{this.users}}
4
@alignColumnLeft={{true}}
5
as |RowColumn user|
6
>
7
<RowColumn>
8
<span>{{user.username}}</span>
9
</RowColumn>
10
<RowColumn>
11
<span>{{user.points}}</span>
12
</RowColumn>
13
</BetaTable>
Copied!
Using a trivial set of hardcoded data for example's sake:
Component tab
1
import Component from '@glimmer/component';
2
import { loadExternalStyle, loadExternalJavascript } from 'client/utils/smart-view-utils';
3
4
export default class extends Component {
5
users = [{
6
username: 'Darth Vador',
7
points: 1500000,
8
}, {
9
username: 'Luke Skywalker',
10
points: 2,
11
}]
12
}
Copied!
To query a custom route of your Forest server as your datasource, you may use this syntax instead:
Component tab
1
import Component from '@glimmer/component';
2
import { inject as service } from '@ember/service';
3
import { tracked } from '@glimmer/tracking';
4
5
export default class extends Component {
6
@service lianaServerFetch;
7
8
@tracked users;
9
10
constructor(...args) {
11
super(...args);
12
this.fetchData();
13
}
14
15
async fetchData() {
16
const response = await this.lianaServerFetch.fetch('/forest/custom-data', {});
17
this.users = await response.json();
18
}
19
}
Copied!

Creating a Bar Chart

This second example shows how you can achieve any format of charts, as you can benefit from external libraries like D3js.
Template tab
1
<div class="c-smart-view">
2
{{this.chart}}
3
</div>
Copied!
Component tab
1
import Component from '@glimmer/component';
2
import { loadExternalStyle, loadExternalJavascript } from 'client/utils/smart-view-utils';
3
import { action } from '@ember/object';
4
import { tracked } from '@glimmer/tracking';
5
6
export default class extends Component {
7
constructor(...args) {
8
super(...args);
9
10
this.loadPlugin();
11
}
12
13
@tracked chart;
14
@tracked loaded = false;
15
16
async loadPlugin() {
17
await loadExternalJavascript('https://d3js.org/d3.v6.min.js');
18
19
this.loaded = true;
20
this.renderChart()
21
}
22
23
async fetchData() {
24
const response = await this.lianaServerFetch.fetch('/forest/custom-data', {});
25
const data = await response.json();
26
return data;
27
}
28
29
@action
30
async renderChart() {
31
if (!this.loaded) { return; }
32
33
const color = 'steelblue';
34
35
// Don't comment the lines below if you want to fetch data from your Forest server
36
// const usersData = await this.fetchData()
37
// const data = Object.assign(usersData.sort((a, b) => d3.descending(a.points, b.points)), {format: "%", y: "↑ Frequency"})
38
39
// To remove if you're using data from your Forest server
40
const alphabet = await d3.csv('https://static.observableusercontent.com/files/09f63bb9ff086fef80717e2ea8c974f918a996d2bfa3d8773d3ae12753942c002d0dfab833d7bee1e0c9cd358cd3578c1cd0f9435595e76901508adc3964bbdc?response-content-disposition=attachment%3Bfilename*%3DUTF-8%27%27alphabet.csv', function(d) {
41
return {
42
name: d.letter,
43
value: +d.frequency
44
};
45
})
46
const data = Object.assign(alphabet.sort((a, b) => d3.descending(a.value, b.value)), {format: "%", y: "↑ Frequency"})
47
48
49
const height = 500;
50
const width = 800;
51
const margin = ({top: 30, right: 0, bottom: 30, left: 40})
52
53
const x = d3.scaleBand()
54
.domain(d3.range(data.length))
55
.range([margin.left, width - margin.right])
56
.padding(0.1)
57
const y = d3.scaleLinear()
58
.domain([0, d3.max(data, d => d.value)]).nice()
59
.range([height - margin.bottom, margin.top])
60
61
const xAxis = g => g
62
.attr("transform", `translate(0,${height - margin.bottom})`)
63
.call(d3.axisBottom(x).tickFormat(i => data[i].username).tickSizeOuter(0))
64
65
const yAxis = g => g
66
.attr("transform", `translate(${margin.left},0)`)
67
.call(d3.axisLeft(y).ticks(null, data.format))
68
.call(g => g.select(".domain").remove())
69
.call(g => g.append("text")
70
.attr("x", -margin.left)
71
.attr("y", 10)
72
.attr("fill", "currentColor")
73
.attr("text-anchor", "start")
74
.text(data.y))
75
76
const svg = d3.create("svg")
77
.attr("viewBox", [0, 0, width, height]);
78
79
svg.append("g")
80
.attr("fill", color)
81
.selectAll("rect")
82
.data(data)
83
.join("rect")
84
.attr("x", (d, i) => x(i))
85
.attr("y", d => y(d.value))
86
.attr("height", d => y(0) - y(d.value))
87
.attr("width", x.bandwidth());
88
89
svg.append("g").call(xAxis);
90
91
svg.append("g").call(yAxis);
92
93
this.chart = svg.node();
94
}
95
}
Copied!
In the above snippet, notice how we import the D3js library. Of course, you can choose to use any other library of your choice.
This bar chart is inspired by this one.
The resulting chart can be resized to fit your use:

Creating a density map

This last example shows how you can achieve virtually anything, since you are basically coding in a sandbox. There's no limit to what you can do with Smart charts.
Template tab
1
<div class="c-smart-view">
2
{{this.chart}}
3
</div>
Copied!
Component tab
1
import Component from '@glimmer/component';
2
import { loadExternalStyle, loadExternalJavascript } from 'client/utils/smart-view-utils';
3
import { action } from '@ember/object';
4
import { tracked } from '@glimmer/tracking';
5
6
export default class extends Component {
7
constructor(...args) {
8
super(...args);
9
10
this.loadPlugin();
11
}
12
13
@tracked chart;
14
@tracked loaded = false;
15
16
async loadPlugin() {
17
await loadExternalJavascript('https://d3js.org/d3.v6.min.js');
18
await loadExternalJavascript('https://unpkg.com/[email protected]');
19
20
this.loaded = true;
21
this.renderChart()
22
}
23
24
@action
25
async renderChart() {
26
if (!this.loaded) { return; }
27
28
const height = 610;
29
const width = 975;
30
const format = d3.format(",.0f");
31
const path = d3.geoPath();
32
33
// This is the JSON for drawing the contours of the map
34
// Ref.: https://github.com/d3/d3-fetch/blob/v2.0.0/README.md#json
35
const us = await d3.json("https://static.observableusercontent.com/files/6b1776f5a0a0e76e6428805c0074a8f262e3f34b1b50944da27903e014b409958dc29b03a1c9cc331949d6a2a404c19dfd0d9d36d9c32274e6ffbc07c11350ee?response-content-disposition=attachment%3Bfilename*%3DUTF-8%27%27counties-albers-10m.json")
36
const features = new Map(topojson.feature(us, us.objects.counties).features.map(d => [d.id, d]))
37
// Population should contain data about the dencity
38
const population = await d3.json('https://static.observableusercontent.com/files/beb56a2d9534662123fa352ffff2db8472e481776fcc1608ee4adbd532ea9ccf2f1decc004d57adc76735478ee68c0fd18931ba01fc859ee4901deb1bee2ed1b?response-content-disposition=attachment%3Bfilename*%3DUTF-8%27%27population.json')
39
40
const data = population.slice(1).map(([population, state, county]) => {
41
const id = state + county;
42
const feature = features.get(id);
43
return {
44
id,
45
position: feature && path.centroid(feature),
46
title: feature && feature.properties.name,
47
value: +population
48
};
49
})
50
51
const radius = d3.scaleSqrt([0, d3.max(data, d => d.value)], [0, 40])
52
53
const svg = d3.create("svg")
54
.attr("viewBox", [0, 0, width, height]);
55
56
svg.append("path")
57
.datum(topojson.feature(us, us.objects.nation))
58
.attr("fill", "#ddd")
59
.attr("d", path);
60
61
svg.append("path")
62
.datum(topojson.mesh(us, us.objects.states, (a, b) => a !== b))
63
.attr("fill", "none")
64
.attr("stroke", "white")
65
.attr("stroke-linejoin", "round")
66
.attr("d", path);
67
68
const legend = svg.append("g")
69
.attr("fill", "#777")
70
.attr("transform", "translate(915,608)")
71
.attr("text-anchor", "middle")
72
.style("font", "10px sans-serif")
73
.selectAll("g")
74
.data(radius.ticks(4).slice(1))
75
.join("g");
76
77
legend.append("circle")
78
.attr("fill", "none")
79
.attr("stroke", "#ccc")
80
.attr("cy", d => -radius(d))
81
.attr("r", radius);
82
83
legend.append("text")
84
.attr("y", d => -2 * radius(d))
85
.attr("dy", "1.3em")
86
.text(radius.tickFormat(4, "s"));
87
88
svg.append("g")
89
.attr("fill", "brown")
90
.attr("fill-opacity", 0.5)
91
.attr("stroke", "#fff")
92
.attr("stroke-width", 0.5)
93
.selectAll("circle")
94
.data(data
95
.filter(d => d.position)
96
.sort((a, b) => d3.descending(a.value, b.value)))
97
.join("circle")
98
.attr("transform", d => `translate(${d.position})`)
99
.attr("r", d => radius(d.value))
100
.append("title")
101
.text(d => `${d.title} ${format(d.value)}`);
102
103
this.chart = svg.node();
104
}
105
}
Copied!
In the above snippet, notice how we import the D3js library. Of course, you can choose to use any other library of your choice.
This density map chart is inspired from this one.
The resulting chart can be resized to fit your use:

Creating a Cohort Chart

This is another example to help you build a Cohort Chart.
Template tab
1
<div class="c-smart-chart">
2
<div id="demo"></div>
3
</div>
Copied!
Component tab
1
import Component from '@glimmer/component';
2
import { action } from '@ember/object';
3
import { tracked } from '@glimmer/tracking';
4
import { inject as service } from '@ember/service';
5
import { loadExternalStyle, loadExternalJavascript } from 'client/utils/smart-view-utils';
6
function isValidHex(color){
7
return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(color);
8
}
9
function shadeColor(color, percent) { //#
10
color = isValidHex(color) ? color : "#3f83a3"; //handling null color;
11
percent = 1.0 - Math.ceil(percent / 10) / 10;
12
var f=parseInt(color.slice(1),16),t=percent<0?0:255,p=percent<0?percent*-1:percent,R=f>>16,G=f>>8&0x00FF,B=f&0x0000FF;
13
return "#"+(0x1000000+(Math.round((t-R)*p)+R)*0x10000+(Math.round((t-G)*p)+G)*0x100+(Math.round((t-B)*p)+B)).toString(16).slice(1);
14
}
15
export default class extends Component {
16
@service lianaServerFetch;
17
@tracked loaging = true;
18
constructor(...args) {
19
super(...args);
20
this.loadPlugin();
21
}
22
async loadPlugin() {
23
await loadExternalJavascript('https://d3js.org/d3.v6.min.js');
24
this.loaging = false;
25
this.renderChart()
26
}
27
getRows(data){
28
var rows = [];
29
var keys = Object.keys(data);
30
var days = [];
31
var percentDays = [];
32
for(var key in keys){
33
if(data.hasOwnProperty(keys[key])) {
34
days = data[keys[key]];
35
percentDays.push(keys[key]);
36
for(var i = 0; i < days.length; i++){
37
percentDays.push(i > 0 ? Math.round((days[i]/days[0] * 100) * 100) / 100 : days[i]);
38
}
39
rows.push(percentDays);
40
percentDays = [];
41
}
42
}
43
return rows;
44
}
45
@action
46
async renderChart() {
47
// To fetch data from the backend
48
// const data = await this.lianaServerFetch.fetch('/forest/custom-route', {});
49
const options = {
50
data : {
51
// You can use any data format, just change the getRows logic
52
"May 3, 2021" : [79, 18, 16, 12, 16, 11, 7, 5],
53
"May 10, 2021" : [168, 35, 28, 30, 24, 12, 10 ],
54
"May 17, 2021" : [188, 42, 32, 34, 25, 18],
55
"May 24, 2021" : [191, 42, 32, 28, 12],
56
"May 31, 2021" : [191, 45, 34, 30],
57
"June 7, 2021" : [184, 42, 32],
58
"June 14, 2021" : [182, 44],
59
},
60
title : "Retention rates by weeks after signup"
61
};
62
var graphTitle = options.title || "Retention Graph";
63
var data = options.data || null;
64
const container = d3.select("#demo").append("div")
65
.attr("class", "box");
66
var header = container.append("div")
67
.attr("class", "box-header with-border");
68
var title = header.append("p")
69
.attr("class", "box-title")
70
.text(graphTitle);
71
var body = container.append("div")
72
.attr("class", "box-body");
73
var table = body.append("table")
74
.attr("class", "table table-bordered text-center");
75
var headData = ["Cohort", "New users", "1", "2", "3", "4", "5", "6", "7"];
76
var tHead = table.append("thead")
77
.append("tr")
78
.attr("class", "retention-thead")
79
.selectAll("td")
80
.data(headData)
81
.enter()
82
.append("td")
83
.attr("class", function (d, i) {
84
if(i == 0)
85
return "retention-date"
86
else
87
return "days"
88
})
89
.text(function (d) {
90
return d;
91
});
92
var rowsData = this.getRows(data);
93
var tBody = table.append("tbody");
94
var rows = tBody.selectAll("tr")
95
.data(rowsData).enter()
96
.append("tr");
97
var cells = rows.selectAll("td")
98
.data(function (row, i) {
99
return row;
100
}).enter()
101
.append("td")
102
.attr("class", function (d, i) {
103
if(i == 0)
104
return "retention-date";
105
else
106
return "days";
107
})
108
.attr("style", function (d, i) {
109
if(i > 1)
110
return "background-color :" + shadeColor("#00c4b4", d);
111
})
112
.append("div")
113
.attr("data-toggle", "tooltip")
114
.text(function (d, i) {
115
return d + (i > 1 ? "%" : "");
116
});
117
}
118
}
Copied!
In the above snippet, notice how we import the D3js library. Of course, you can choose to use any other library of your choice.
Style tab
1
.c-smart-chart {
2
display: flex;
3
white-space: normal;
4
bottom: 0;
5
left: 0;
6
right: 0;
7
top: 0;
8
background-color: var(--color-beta-surface);
9
}
10
.box{
11
position:relative;
12
border-radius:3px;
13
background:#ffffff;
14
width:100%;
15
}
16
.box-body{
17
max-height:500px;
18
overflow:auto;
19
border-top-left-radius:0;
20
border-top-right-radius:0;
21
border-bottom-right-radius:3px;
22
border-bottom-left-radius:3px;
23
}
24
.box-header{
25
color:#444;
26
display:block;
27
padding:10px;
28
position:relative
29
}
30
.box-header .box-title{
31
display:inline-block;
32
font-size:18px;
33
margin:0;
34
line-height:1;
35
}
36
.box-title{
37
display:inline-block;font-size:18px;margin:0;line-height:1
38
}
39
.retention-thead, .retention-date{
40
background-color: #cfcfcf;
41
font-weight: 700;
42
padding