d3js multi-line-chart not auto updating

341 views
Skip to first unread message

Venkat Ram

unread,
Oct 10, 2016, 12:46:44 PM10/10/16
to d3-js

I created multi line chart using mbostok and d3noob as reference.https://gist.github.com/d3noob/d8be922a10cb0b148cd5.

I want it to refresh after 3 secs. When it refreshes, the first line disappers. Please suggest.



<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */

body { font: 12px Arial;}

path { 
    stroke: steelblue;
    stroke-width: 2;
    fill: none;
}

.axis path,
.axis line {
    fill: none;
    stroke: grey;
    stroke-width: 1;
    shape-rendering: crispEdges;
}

</style>
<body>

<!-- load the d3.js library -->    
<script src="http://d3js.org/d3.v3.min.js"></script>

<script>

// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
    width = 900 - margin.left - margin.right,
    height = 570 - margin.top - margin.bottom;

// Parse the date / time
var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;


// Set the ranges
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear().range([height, 0]);

//var y = d3.scale.range([height, 0]);

var axisTimeFormat = d3.time.format.multi([
    [".%L", function(d) { return d.getMilliseconds(); }],
    [":%S", function(d) { return d.getSeconds(); }],
    ["%H:%M", function(d) { return d.getMinutes(); }],
    ["%H:%M", function(d) { return d.getHours(); }],
    ["%a %d", function(d) { return d.getDay() && d.getDate() != 1; }],
    ["%b %d", function(d) { return d.getDate() != 1; }],
    ["%B", function(d) { return d.getMonth(); }],
    ["%Y", function() { return true; }]
 ]);


// Define the axes
var xAxis = d3.svg.axis().scale(x)
    .orient("bottom").tickFormat(d3.time.format("%H:%M"));

var yAxis = d3.svg.axis().scale(y)
    .orient("left").ticks(10);

// Define the line
var valueline = d3.svg.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.close); });

// Adds the svg canvas
var svg = d3.select("body")
    .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
    .append("g")
        .attr("transform", 
              "translate(" + margin.left + "," + margin.top + ")");

// Get the data
d3.tsv("final_report_multi.tsv", function(error, data) {
    data.forEach(function(d) {
        //console.log(d.d);
        d.date = parseDate(d.tim);
        //d.date = '2016-07-10 22:20:10';
        //d.date=d.date
        d.close = d.count;
        //console.log(d.date);
        //console.log(d.close);

    });

//data=data.sort(function(a, b) {
 //               return d3.ascending(a.tim,b.tim);
 //           });

    // Scale the range of the data
    x.domain(d3.extent(data, function(d) { return d.date; }));
    y.domain([0, d3.max(data, function(d) { return d.close; })]);
    //y.domain(d3.extent(data, function(d) { return d.count; }));
    y.domain([0,500]);

 var color = d3.scale.category10();

 // Nest the entries by symbol
    var dataNest = d3.nest()
        .key(function(d) {return d.dept;})
        .entries(data);

    // Loop through each symbol / key
    dataNest.forEach(function(d) {
        console.log(d.values)
        svg.append("path")
            .attr("class", "line")
            .style("stroke", function() {
                return d.color = color(d.key); })
            .attr("d", valueline(d.values)); 
    });


    // Add the valueline path.
  //  svg.append("path")
 //       .attr("class", "line")
 //       .attr("d", valueline(data));

    // Add the X Axis
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    // Add the Y Axis
    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);

});



var inter = setInterval(function() {
                updateData();
        }, 3000); 


        // ** Update data section (Called from the onclick)
function updateData() {

    // Get the data again
  d3.tsv("final_report_multi.tsv", function(error, data) {
    data.forEach(function(d) {
        d.date = parseDate(d.tim);
        d.close = d.count;
        console.log(d.date);
        console.log(d.close);

    });

        // Scale the range of the data again 
        x.domain(d3.extent(data, function(d) { return d.date; }));
        y.domain([0, d3.max(data, function(d) { return d.close; })]);
       //  y.domain([d3.extent(data, function(d) { return d.close; })]);
        y.domain([0,100]);

    // Select the section we want to apply our changes to
    var svg = d3.select("body").transition();

     // Nest the entries by symbol
    var dataNest = d3.nest()
        .key(function(d) {return d.dept;})
        .entries(data);

    // Loop through each symbol / key
    dataNest.forEach(function(d) {
        var svg = d3.select("body").transition();
        console.log(d.values)
        svg.select(".line")   // change the line
            .duration(750)
            .attr("d", valueline(d.values)); 
        svg.select(".x.axis") // change the x axis
            .duration(750)
            .call(xAxis);
        svg.select(".y.axis") // change the y axis
            .duration(750)
            .call(yAxis)
    });

    // Make the changes
   //     svg.select(".line")   // change the line
   //         .duration(750)
   //         .attr("d", valueline(data));
  //      svg.select(".x.axis") // change the x axis
  //          .duration(750)
  //          .call(xAxis);
  //      svg.select(".y.axis") // change the y axis
  //          .duration(750)
  //          .call(yAxis);

    });
}


</script>

</body>


tsv file i used

dept    tim count
home    2016-10-06 23:15:44 220 
home    2016-10-06 23:40:44 150 
toys    2016-10-06 23:10:44 400
toys    2016-10-06 23:30:44 1000

Venkat Ram

unread,
Oct 11, 2016, 2:02:08 PM10/11/16
to d3-js
Hi Experts, Please suggest

Let me explain my issue again. Initially both lines are displayed fine. The issue i have is that after transition, the first line for dept=home disappears. In the update data section, Some how the nest function and data selected is not correctly fetching the first value. Its fetching the second set of rows for dept=toys 

Seemant Kulleen

unread,
Oct 12, 2016, 3:36:17 AM10/12/16
to d3-js
Hi Venkat,

I had to massage your code a bit to get it to work, but I managed to do that.  And I've changed the .forEach() loop where you draw the lines into a more d3 oriented way, using data joins and the enter-update pattern.



I'm unclear what the update() function is for, as the dataset doesn't change.  Can you help understand what is being updated?

Cheers,
Seemant


--
Oakland Finish Up Weekend
Be Amazed.  Be Amazing.
Get Mentored | Get Inspired | Finish Up
http://oaklandfinishup.com


--
You received this message because you are subscribed to the Google Groups "d3-js" group.
To unsubscribe from this group and stop receiving emails from it, send an email to d3-js+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages