lighter
lighter

Reputation: 2806

D3 LineChart with mouse move and show point

I created a lineChart by d3(4.12.2). And I want to add mouse move event. It's not work for me. This is my code jsfiddle.

Thanks your help.

$(document).ready(function () {
    function lineChart(elementId, xMax, yMax, xMin, yMin, x, y, dataset) {
        var margin = {
            top: 60,
            right: 40,
            bottom: 120,
            left: 60
        };
        var w = 700;
        var h = 300;
        var width = w + margin.left + margin.right;
        var height = h + margin.top + margin.bottom;

        var xScale = d3.scaleTime()
            .domain([xMin, xMax])
            .range([0, w]);
        var yScale = d3.scaleLinear().domain([yMin, yMax]).range([h, 0]);

        var line = d3.line()
            .x(function (d) {
                return xScale(d[x]);
            })
            .y(function (d) {
                return yScale(d[y]);
            });

        var svg = d3.select(`#${elementId}`).append('svg')
            .attr('width', width)
            .attr('height', height)
            .append('g')
            .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

        svg.append("rect")
        .attr("width", width)
        .attr("height", height)
        .style("fill", "transparent")
        .on('mousemove', identifyMouse);

        svg.append('g')
        .attr('class', 'x axis')
        .attr('transform', 'translate(0,' + h + ')')
        .call(d3.axisBottom(xScale)
            .tickFormat(d3.timeFormat('%Y-%m-%d %H:%M:%S')))
        .selectAll('text')
        .style("text-anchor", "end")
        .attr("dx", "-.8em")
        .attr("dy", ".15em")
        .attr('transform', 'rotate(-65)');

        svg.append('g')
        .attr('class', 'y axis')
        .attr('transform', 'translate(0,0)')
        .call(d3.axisLeft(yScale));
        svg.append('path').datum(dataset).attr('fill', 'none')
        .attr('stroke', 'DodgerBlue')
        .attr('stroke-width', 1)
        .attr('d', line);

        var bisectDate = d3.bisector(function (d) {
                return d[x];
            }).left;

        var circle = svg.append('circle')
            .style("fill", "black")
            .style("stroke", "blue")
            .attr('r', 5);

        function identifyMouse() {
            console.log(dataset.length);
            var x0 = xScale.invert(d3.mouse(this)[0]);
            console.log('old', x0);
            x0 = new Date(`'${x0}'`).getTime();
            console.log('new', x0);
            var i = bisectDate(dataset, x0);
            console.log(i);
            var smaller = dataset[i - 1];
            console.log('smaller', smaller);
            var larger = dataset[i];
            console.log('larger', larger);
            var d = x0 - smaller[x] > larger[x] - x0 ? larger : smaller;

            circle.attr("transform", "translate(" + xScale(d[x]) + "," + yScale(d[y]) + ")");
        }
    }
});

Upvotes: 1

Views: 235

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

Instead of

var bisectDate = d3.bisector(function(d){ return d[x]; }).right;

it should have been

var bisectDate = d3.bisector(function(a, b){ return a[x] - b; }).right;

Then for bisect, to work its assumed that the dataset is sorted.

so sort the data like this before passing to bisect function:

  dataset.sort(function(a, b){
        return a[x]-b[x];
            });

Finally, for getting the bisected data do:

var i = bisectDate(dataset, x0.getTime()); //sincex0is date object.

working code here

EDIT

How do you know to use a[x] - b

In this line below. var i = bisectDate(dataset, x0.getTime())

here x0 is a date object.

So in the function:

d3.bisector(function(a, b){ return a[x] - b; }).right;

so a[x] is your unixtime which is tie stamp and b as mentioned is also time stamp. So here in bisector function we subtracting both time stamps to find the closest point.

Upvotes: 1

Related Questions