Search code examples
d3.jslabelreal-time

Display real time data in text label d3.js


I have a line graph that is updating as data is pulled in at 5 second intervals from a database.

https://gist.github.com/Majella/5fc4cd5f41a6ddf2df23

I wanted to add a label to the top right hand corner of the graph that will display the date/time (stored as variable dateTimeTaken) and update this label as the new data pulled in?

I've been searching online and can't seem to find an example of this anywhere - can anyone help?


Solution

  • It should be quite easy. Based on your gist, something like:

    d3.json("getdata.php", function(error,data) {
      data.forEach(function(d) {
        d.dateTimeTaken = parseDate(d.dateTimeTaken);
        d.reading = +d.reading;
      });
    var maxDate = d3.max( data, function(d) { return d.dateTimeTaken; } 
    
    svg.selectAll( ".timeDisplay" )
      .data( [maxDate] )
      .text( function(d) { return d; } )
      .enter()
      .append("text")
      .attr("class", "timeDisplay" )
      .attr("x", width )
      .attr("y", 0)
      .attr("text-anchor", "end" )
      .text( dateTimeTaken );
    

    Put this in your "updateData" function. Given that you are receiving multiple data items, you may need to do a "d3.max()" call on the data to figure out which date you want to display.