使用json数据的d3.js实时折线图

时间:2018-08-24 12:21:17

标签: d3.js linechart

请看小提琴并帮助我。

$(".ui.toggle")
      .checkbox({
        onChecked: function () {
          console.log("checked");
          str_btn_value = 1;
          vari_timer = setInterval(updateData, 1000);

        },
        onUnchecked: function () {
          console.log("unchecked");
          str_btn_value = 0;
          clearInterval(vari_timer);
        }
      });

      var celcius_array = [], str_btn_value = 0, vari_timer, sl_no = 0;

       function randomNumberBounds(min, max) {
      return Math.floor(Math.random() * max) + min;
    }

     function updateData() {
      if (str_btn_value === 1) {
        var now = new Date();
        var c1 = randomNumberBounds(0, 75);
        var f1 = c1 * 9 / 5 + 32;
        var c2 = randomNumberBounds(0, 75);
        var f2 = c2 * 9 / 5 + 32;
        var c3 = randomNumberBounds(0, 75);
        var f3 = c3 * 9 / 5 + 32;
        var lineData = {
          // Time: now.toLocaleString(),
          Time: now,
          TC1: c1,
          TC2: c2,
          TC3: c3,
          TF1: f1,
          TF2: f2,
          TF3: f3
        };
        celcius_array.push(lineData);
        console.log(celcius_array);
        document.getElementById('gen_temp_data_c').value = JSON.stringify(celcius_array);
           drawgraph();
      }
    }


    function drawgraph() {
      d3.selectAll("svg > *").remove();
      // Draw a line chart
      var svg = d3.select('svg'),
        margin = { top: 20, right: 50, bottom: 30, left: 50 },
        width = +svg.attr('width') - margin.left - margin.right,
        height = +svg.attr('height') - margin.top - margin.bottom,
        g = svg.append('g').attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
      // Graph title
      g.append('text')
        .attr('x', (width / 2))
        .attr('y', 0 - (margin.top / 3))
        .attr('text-anchor', 'middle')
        .style('font-size', '16px')
        .text('Temperature chart');
      // Function to convert a string into a time
      // var parseTime = d3.time.format("%Y-%m-%dT%H:%M:%S.%LZ").parse;
      var parseTime = d3.time.format("%Y-%m-%dT%H:%M:%S.%LZ").parse;
      // Function to show specific time format
      // var formatTime = d3.time.format('%e %B');
      var formatTime = d3.time.format('%X');
      // Set the X scale
      var x = d3.time.scale().range([0, width], 0.5);
      // Set the Y scale
      var y = d3.scale.linear().range([height, 0]);
      // Set the Y1 scale
      var y1 = d3.scale.linear().range([height, 0]);
      // Set the color scale
      var color = d3.scale.category10();

      var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

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

      var yAxisRight = d3.svg.axis()
        .scale(y1)
        .orient("right");

      var line = d3.svg.line()
        // .interpolate("basis")
        .x(function (d) {
          return x(d.date);
        })
        .y(function (d) {
          return y(d.worth);
        });

      // load the data\
      var data = JSON.parse(document.getElementById("gen_temp_data_c").value);
      // d3.json("data.json", function(error, data) {
      // console.log(data);
      // Select the important columns
      color.domain(d3.keys(data[0]).filter(function (key) {
        return key !== "Time" && key !== "_id";
      }));
      // Correct the types
      data.forEach(function (d) {
        d.date = parseTime(d.Time);
      });
      console.log(data);

      var temp_values = color.domain().map(function (name) {
        return {
          name: name,
          values: data.map(function (d) {
            return {
              date: d.date,
              worth: +d[name]
            };
          })
        };
      });
      console.log(temp_values)
      // Set the X domain
      x.domain(d3.extent(data, function (d) {
        return d.date;
      }));
      // Set the Y domain
      y.domain([
        d3.min(temp_values, function (c) {
          return d3.min(c.values, function (v) {
            return v.worth;
          });
        }),
        d3.max(temp_values, function (c) {
          return d3.max(c.values, function (v) {
            return v.worth;
          });
        })
      ]);
        // Set the Y1 domain
        y1.domain([
        d3.min(temp_values, function (c) {
          return d3.min(c.values, function (v) {
            return v.worth;
          });
        }),
        d3.max(temp_values, function (c) {
          return d3.max(c.values, function (v) {
            return v.worth;
          });
        })
      ]);
      // Set the X axis
      g.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);
      // Set the Y axis
      g.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Celcius");
              // Set the Y1 axis
      g.append("g")
        .attr("class", "y axis ")
        .call(yAxisRight)
        .append("text")
        .attr("transform", "translate(" + width + " ,0)", "rotate(-90)")    
        .attr("y1", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Farenheit");

      // Draw the lines
      var temp_value_line = g.selectAll(".temp_value_line")
        .data(temp_values)
        .enter().append("g")
        .attr("class", "temp_value_line");

      temp_value_line.append("path")
        .attr("class", "line")
        .attr("d", function (d) {
          return line(d.values);
        })
        .style("stroke", function (d) {
          return color(d.name);
        });
      // Add the circles
      temp_value_line.append("g").selectAll("circle")
        .data(function (d) { return d.values })
        .enter()
        .append("circle")
        .attr("r", 2)
        .attr("cx", function (dd) { return x(dd.date) })
        .attr("cy", function (dd) { return y(dd.worth) })
        .attr("fill", "none")
        .attr("stroke", function (d) { return color(this.parentNode.__data__.name) });
      // Add label to the end of the line
      temp_value_line.append("text")
        .attr("class", "label")
        .datum(function (d) {
          return {
            name: d.name,
            value: d.values[d.values.length - 1]
          };
        })
        .attr("transform", function (d) {
          return "translate(" + x(d.value.date) + "," + y(d.value.worth) + ")";
        })
        .attr("x", 3)
        .attr("dy", ".35em")
        .text(function (d) {
          return d.name;
        });

      // Add the mouse line
      var mouseG = g.append("g")
        .attr("class", "mouse-over-effects");

      mouseG.append("path")
        .attr("class", "mouse-line")
        .style("stroke", "black")
        .style("stroke-width", "1px")
        .style("opacity", "0");

      var lines = document.getElementsByClassName('line');

      var mousePerLine = mouseG.selectAll('.mouse-per-line')
        .data(temp_values)
        .enter()
        .append("g")
        .attr("class", "mouse-per-line");

      mousePerLine.append("circle")
        .attr("r", 7)
        .style("stroke", function (d) {
          return color(d.name);
        })
        .style("fill", "none")
        .style("stroke-width", "2px")
        .style("opacity", "0");

      mousePerLine.append("text")
        .attr("class", "hover-text")
        .attr("dy", "-1em")
        .attr("transform", "translate(10,3)");

      // Append a rect to catch mouse movements on canvas
      mouseG.append('svg:rect')
        .attr('width', width)
        .attr('height', height)
        .attr('fill', 'none')
        .attr('pointer-events', 'all')
        .on('mouseout', function () { // on mouse out hide line, circles and text
          d3.select(".mouse-line")
            .style("opacity", "0");
          d3.selectAll(".mouse-per-line circle")
            .style("opacity", "0");
          d3.selectAll(".mouse-per-line text")
            .style("opacity", "0");
        })
        .on('mouseover', function () { // on mouse in show line, circles and text
          d3.select(".mouse-line")
            .style("opacity", "1");
          d3.selectAll(".mouse-per-line circle")
            .style("opacity", "1");
          d3.selectAll(".mouse-per-line text")
            .style("opacity", "1");
        })
        .on('mousemove', function () { // mouse moving over canvas
          var mouse = d3.mouse(this);

          d3.selectAll(".mouse-per-line")
            .attr("transform", function (d, i) {

              var xDate = x.invert(mouse[0]),
                bisect = d3.bisector(function (d) { return d.date; }).left;
              idx = bisect(d.values, xDate);

              d3.select(this).select('text')
                .text(y.invert(y(d.values[idx].worth)).toFixed(2));

              d3.select(".mouse-line")
                .attr("d", function () {
                  var data = "M" + x(d.values[idx].date) + "," + height;
                  data += " " + x(d.values[idx].date) + "," + 0;
                  return data;
                });
              return "translate(" + x(d.values[idx].date) + "," + y(d.values[idx].worth) + ")";
            });
        });



    }

我正在使用d3.js绘制图表,并且在任何时候输入的数据都应为json数据,并且应为引号。 使用json数据的d3.js实时折线图不会更新时间刻度。 我需要实时实时更新每个生成的数据。 我创建了json数据并正确创建了svg,但是我需要使用x轴时间格式[HH:MM:SS]和y1轴[Celcius]和y2轴[Farenheit]更新每个数据。 https://jsfiddle.net/manikandanpachaiyappan/v3Lok6w9/

0 个答案:

没有答案