WebstraDev
WebstraDev

Reputation: 551

Line chart based on formula

Is it possible to make a d3 multi-line line chart based on a formula instead of data?

E.g. the formula could be

Y = aX + bZ + cW

Ideally I would bind the a, b and c to dropdown menus so that I can manipulate the data with the menus. But the problem for me is building the chart based on a formula instead of data.

Upvotes: 2

Views: 746

Answers (1)

Gabriel Florit
Gabriel Florit

Reputation: 2918

Use the dropdowns to create your data.

Say you want to create f(x) = sin(a * sin(b * sin(c * sin(x)))). Add three sliders to your page and draw the chart based on their values:

// Grab slider values
var a = document.querySelector('#a').value;
var b = document.querySelector('#b').value;
var c = document.querySelector('#c').value;

// Construct data from a, b, c
var data = d3.range(-10, 10, 0.01).map(function(v) {
    return {
        x: v,
        y: sin(a * sin(b * sin(c * sin(v))))
    };
});

// JOIN
var paths = svg.selectAll('path.line')
    .data([data]);

// ENTER
paths.enter().append('path')
    .attr('class', 'line')
// ENTER + UPDATE
    .merge(paths)
    .transition()
    .duration(500)
    .attr('d', line);

Here's the three-slider chart: https://bl.ocks.org/gabrielflorit/14435cead80c690105ebbbc35b75796f, with a GIF (because why not).

enter image description here

Upvotes: 5

Related Questions