Как разрешить ошибку TypeError: string.slice на интерактивной диаграмме из нескольких серий? - PullRequest
0 голосов
/ 28 мая 2018

Я программирую интерактивный мультисерийный график.

Я выбираю дизайн из этого: http://bl.ocks.org/DStruths/9c042e3a6b66048b5bd4, и я адаптировал его к данным json

У меня проблемаОшибка типа: string.slice не является функцией в строке 203

Знаете ли вы, как ее решить?

Мой код:

    <!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Issues Ratings</title>
<style>

body {
  font: 10px sans-serif;
}

.axis path,
.axis line, 
.axis1 path,
.axis1 line {
  fill: none;
  stroke: #E6E7E8;
  shape-rendering: crispEdges;
}

.x.axis path, .x.axis1 path {
  display: none;
}

.line {
  fill: none;
  stroke-width: 1.5px;
}

.legend-box {
  cursor: pointer;  
}

#mouse-tracker {
  stroke: #E6E7E8;
  stroke-width: 1px;
}

.hover-line { 
  stroke: #E6E7E8;
  fill: none;
  stroke-width: 1px;
  left: 10px;
  shape-rendering: crispEdges;
  opacity: 1e-6;
}

.hover-text {
  stroke: none;
  font-size: 30px;
  font-weight: bold;
  fill: #000000;
}

.tooltip {
  font-weight: normal;
}

.brush .extent {
  stroke: #FFF;
  shape-rendering: crispEdges;
}

</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.js"></script>

<script>

var margin = {top: 20, right: 200, bottom: 100, left: 50},
    margin2 = { top: 430, right: 10, bottom: 20, left: 40 },
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom,
    height2 = 500 - margin2.top - margin2.bottom;

var parseTime = d3.time.format("%m/%d/%Y %H:%M:%S %p").parse;
var bisectDate = d3.bisector(function(d) { return d.date; }).left;

var xScale = d3.time.scale()
    .range([0, width]),

    xScale2 = d3.time.scale()
    .range([0, width]); // Duplicate xScale for brushing ref later

var yScale = d3.scale.linear()
    .range([height, 0]);

// 40 Custom DDV colors 
var color = d3.scale.ordinal().range(["#48A36D",  "#56AE7C",  "#64B98C", "#72C39B", "#80CEAA", "#80CCB3", "#7FC9BD", "#7FC7C6", "#7EC4CF", "#7FBBCF", "#7FB1CF", "#80A8CE", "#809ECE", "#8897CE", "#8F90CD", "#9788CD", "#9E81CC", "#AA81C5", "#B681BE", "#C280B7", "#CE80B0", "#D3779F", "#D76D8F", "#DC647E", "#E05A6D", "#E16167", "#E26962", "#E2705C", "#E37756", "#E38457", "#E39158", "#E29D58", "#E2AA59", "#E0B15B", "#DFB95C", "#DDC05E", "#DBC75F", "#E3CF6D", "#EAD67C", "#F2DE8A"]);  


var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient("bottom"),

    xAxis2 = d3.svg.axis() // xAxis for brush slider
    .scale(xScale2)
    .orient("bottom");    

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

var line = d3.svg.line()
    .interpolate("basis")
    .x(function(d) { return xScale(d.date); })
    .y(function(d) { return yScale(d.temperature); })
    .defined(function(d) { return d.temperature; });  // Hiding line value defaults of 0 for missing data

var maxY; // Defined later to update yAxis

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

// Create invisible rect for mouse tracking
svg.append("rect")
    .attr("width", width)
    .attr("height", height)                                    
    .attr("x", 0) 
    .attr("y", 0)
    .attr("id", "mouse-tracker")
    .style("fill", "white"); 

//for slider part-----------------------------------------------------------------------------------

var context = svg.append("g") // Brushing context box container
    .attr("transform", "translate(" + 0 + "," + 410 + ")")
    .attr("class", "context");

//append clip path for lines plotted, hiding those part out of bounds
svg.append("defs")
  .append("clipPath") 
    .attr("id", "clip")
    .append("rect")
    .attr("width", width)
    .attr("height", height); 

//end slider part----------------------------------------------------------------------------------- 

d3.json("testSerialisation_v5.ujson", function(error, data) {
              if (error) throw error;

            var data = data["Session_test"][0]["datas_lines"];

            let responses = [];

            data.forEach(obj => {
                if (obj.log_time !== "No data") {
                    let iterator = 0;
                    let final = {};
                    obj.datas_line.forEach(d => {
                    final[iterator.toString()] = d;
                    iterator++;
                    });
                    final.log_time = obj.log_time;
                    responses.push(final);
                }
            });

            var dateKey = d3.keys(responses[0]);
            var i = dateKey.indexOf('log_time')
                if(i != -1) {
                    dateKey.splice(i, 1);
                }

            var temp_list = dateKey.map(function(d) { 
                return {
                    id:d,
                    values: responses.map( function(e) {
                        return {
                            date: e.log_time,
                            temperature: e[d]
                        };
                    })
                } 
            });

  xScale.domain(d3.extent(responses, function(d) { return parseTime(d.log_time); })); // extent = highest and lowest points, domain is data, range is bouding box

  yScale.domain([
    d3.min(temp_list, function(c) { return d3.min(c.values, function(d) { return d.temperature; }); }),
    d3.max(temp_list, function(c) { return d3.max(c.values, function(d) { return d.temperature; }); })
  ]);

  xScale2.domain(xScale.domain()); // Setting a duplicate xdomain for brushing reference later

 //for slider part-----------------------------------------------------------------------------------

 var brush = d3.svg.brush()//for slider bar at the bottom
    .x(xScale2) 
    .on("brush", brushed);

  context.append("g") // Create brushing xAxis
      .attr("class", "x axis1")
      .attr("transform", "translate(0," + height2 + ")")
      .call(xAxis2);

  var contextArea = d3.svg.area() // Set attributes for area chart in brushing context graph
    .interpolate("monotone")
    .x(function(d) { return xScale2(parseTime(new Date(d.log_time))); }) // x is scaled to xScale2
    .y0(height2) // Bottom line begins at height2 (area chart not inverted) 
    .y1(0); // Top line of area, 0 (area chart not inverted)

  //plot the rect as the bar at the bottom
  context.append("path") // Path is created using svg.area details
    .attr("class", "area")
    .attr("d", contextArea(temp_list[0].values)) // pass first categories data .values to area path generator 
    .attr("fill", "#F1F1F2");

  //append the brush for the selection of subsection  
  context.append("g")
    .attr("class", "x brush")
    .call(brush)
    .selectAll("rect")
    .attr("height", height2) // Make brush rects same height 
      .attr("fill", "#E6E7E8");  
  //end slider part-----------------------------------------------------------------------------------

  // draw line graph
  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("x", -10)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Issues Rating");

  var issue = svg.selectAll(".issue")
      .data(temp_list) // Select nested data and append to new svg group elements
    .enter().append("g")
      .attr("class", "issue");   

  issue.append("path")
      .attr("class", "line")
      .style("pointer-events", "none") // Stop line interferring with cursor
      .attr("id", function(d) {
        return "line-" + d.id.replace(" ", "").replace("/", ""); // Give line id of line-(insert issue name, with any spaces replaced with no spaces)
      })
      .attr("d", function(d) { 
        return d.visible ? line(d.values) : null; // If array key "visible" = true then draw line, if not then don't 
      })
      .attr("clip-path", "url(#clip)")//use clip path to make irrelevant part invisible
      .style("stroke", function(d) { return color(d.id); });

  // draw legend
  var legendSpace = 450 / temp_list.length; // 450/number of issues (ex. 40)    

  issue.append("rect")
      .attr("width", 10)
      .attr("height", 10)                                    
      .attr("x", width + (margin.right/3) - 15) 
      .attr("y", function (d, i) { return (legendSpace)+i*(legendSpace) - 8; })  // spacing
      .attr("fill",function(d) {
        return d.visible ? color(d.id) : "#F1F1F2"; // If array key "visible" = true then color rect, if not then make it grey 
      })
      .attr("class", "legend-box")

      .on("click", function(d){ // On click make d.visible 
        d.visible = !d.visible; // If array key for this data selection is "visible" = true then make it false, if false then make it true

        maxY = findMaxY(temp_list); // Find max Y rating value categories data with "visible"; true
        yScale.domain([0,maxY]); // Redefine yAxis domain based on highest y value of categories data with "visible"; true
        svg.select(".y.axis")
          .transition()
          .call(yAxis);   

        issue.select("path")
          .transition()
          .attr("d", function(d){
            return d.visible ? line(d.values) : null; // If d.visible is true then draw line for this d selection
          })

        issue.select("rect")
          .transition()
          .attr("fill", function(d) {
          return d.visible ? color(d.id) : "#F1F1F2";
        });
      })

      .on("mouseover", function(d){

        d3.select(this)
          .transition()
          .attr("fill", function(d) { return color(d.id); });

        d3.select("#line-" + d.id.replace(" ", "").replace("/", ""))
          .transition()
          .style("stroke-width", 2.5);  
      })

      .on("mouseout", function(d){

        d3.select(this)
          .transition()
          .attr("fill", function(d) {
          return d.visible ? color(d.id) : "#F1F1F2";});

        d3.select("#line-" + d.id.replace(" ", "").replace("/", ""))
          .transition()
          .style("stroke-width", 1.5);
      })

  issue.append("text")
      .attr("x", width + (margin.right/3)) 
      .attr("y", function (d, i) { return (legendSpace)+i*(legendSpace); })  // (return (11.25/2 =) 5.625) + i * (5.625) 
      .text(function(d) { return d.id; }); 

  // Hover line 
  var hoverLineGroup = svg.append("g") 
            .attr("class", "hover-line");

  var hoverLine = hoverLineGroup // Create line with basic attributes
        .append("line")
            .attr("id", "hover-line")
            .attr("x1", 10).attr("x2", 10) 
            .attr("y1", 0).attr("y2", height + 10)
            .style("pointer-events", "none") // Stop line interferring with cursor
            .style("opacity", 1e-6); // Set opacity to zero 

  var hoverDate = hoverLineGroup
        .append('text')
            .attr("class", "hover-text")
            .attr("y", height - (height-40)) // hover date text position
            .attr("x", width - 150) // hover date text position
            .style("fill", "#E6E7E8");

  var columnNames = d3.keys(responses[0]); //grab the key values from your first data row

  var focus = issue.select("g") // create group elements to house tooltip text
      .data(columnNames) // bind each column name date to each g element
    .enter().append("g") //create one <g> for each columnName
      .attr("class", "focus"); 

  focus.append("text") // http://stackoverflow.com/questions/22064083/d3-js-multi-series-chart-with-y-value-tracking
        .attr("class", "tooltip")
        .attr("x", width + 20) // position tooltips  
        .attr("y", function (d, i) { return (legendSpace)+i*(legendSpace); }); // (return (11.25/2 =) 5.625) + i * (5.625) // position tooltips       

  // Add mouseover events for hover line.
  d3.select("#mouse-tracker") // select chart plot background rect #mouse-tracker
  .on("mousemove", mousemove) // on mousemove activate mousemove function defined below
  .on("mouseout", function() {
      hoverDate
          .text(null) // on mouseout remove text for hover date

      d3.select("#hover-line")
          .style("opacity", 1e-6); // On mouse out making line invisible
  });

  function mousemove() { 
      var mouse_x = d3.mouse(this)[0]; // Finding mouse x position on rect
      var graph_x = xScale.invert(mouse_x); // 

      //var mouse_y = d3.mouse(this)[1]; // Finding mouse y position on rect
      //var graph_y = yScale.invert(mouse_y);
      //console.log(graph_x);

      var format = d3.time.format('%m/%d %H:%M:%S'); // Format hover date text to show three letter month and full year

      hoverDate.text(format(graph_x)); // scale mouse position to xScale date and format it to show month and year

      d3.select("#hover-line") // select hover-line and changing attributes to mouse position
          .attr("x1", mouse_x) 
          .attr("x2", mouse_x)
          .style("opacity", 1); // Making line visible

      // Legend tooltips // http://www.d3noob.org/2014/07/my-favourite-tooltip-method-for-line.html

      var x0 = xScale.invert(d3.mouse(this)[0]), /* d3.mouse(this)[0] returns the x position on the screen of the mouse. xScale.invert function is reversing the process that we use to map the domain (date) to range (position on screen). So it takes the position on the screen and converts it into an equivalent date! */
      i = bisectDate(responses, x0, 1), // use our bisectDate function that we declared earlier to find the index of our data array that is close to the mouse cursor
      /*It takes our data array and the date corresponding to the position of or mouse cursor and returns the index number of the data array which has a date that is higher than the cursor position.*/
      d0 = responses[i - 1],
      d1 = responses[i],
      /*d0 is the combination of date and rating that is in the data array at the index to the left of the cursor and d1 is the combination of date and close that is in the data array at the index to the right of the cursor. In other words we now have two variables that know the value and date above and below the date that corresponds to the position of the cursor.*/
      d = x0 - new Date(d0.log_time) > new Date(d1.log_time) - x0 ? d1 : d0;
      /*The final line in this segment declares a new array d that is represents the date and close combination that is closest to the cursor. It is using the magic JavaScript short hand for an if statement that is essentially saying if the distance between the mouse cursor and the date and close combination on the left is greater than the distance between the mouse cursor and the date and close combination on the right then d is an array of the date and close on the right of the cursor (d1). Otherwise d is an array of the date and close on the left of the cursor (d0).*/

      //d is now the data row for the date closest to the mouse position

      focus.select("text").text(function(columnName){
         //because you didn't explictly set any data on the <text>
         //elements, each one inherits the data from the focus <g>

         return (d[columnName]);
      });
  }; 

  //for brusher of the slider bar at the bottom
  function brushed() {

    xScale.domain(brush.empty() ? xScale2.domain() : brush.extent()); // If brush is empty then reset the Xscale domain to default, if not then make it the brush extent 

    svg.select(".x.axis") // replot xAxis with transition when brush used
          .transition()
          .call(xAxis);

    maxY = findMaxY(temp_list); // Find max Y rating value categories data with "visible"; true
    yScale.domain([0,maxY]); // Redefine yAxis domain based on highest y value of categories data with "visible"; true

    svg.select(".y.axis") // Redraw yAxis
      .transition()
      .call(yAxis);   

    issue.select("path") // Redraw lines based on brush xAxis scale and domain
      .transition()
      .attr("d", function(d){
          return d.visible ? line(d.values) : null; // If d.visible is true then draw line for this d selection
      });

  };      

}); // End Data callback function

  function findMaxY(temp_list){  // Define function "findMaxY"
    return d3.max(temp_list, function(c) { return d3.max(c.values, function(d) { return d.temperature; }); });
  }

</script>
</html>

и мои данные:

        {
"Session_test": [{
    "datas_lines": [{
            "datas_line": [],
            "log_time": "No data"
        },
        {
            "datas_line": [],
            "log_time": "No data"
        },
        {
            "datas_line": [],
            "log_time": "No data"
        },
        {
            "datas_line": [
                "157",
                "158",
                "157",
                "157",
                "157",
                "158",
                "159",
                "161",
                "160",
                "160",
                "159",
                "158",
                "159",
                "160",
                "160",
                "160",
                "160",
                "161",
                "160",
                "161",
                "159",
                "161",
                "161",
                "158",
                "161",
                "159",
                "160",
                "157"
            ],
            "log_time": "5/18/2017 4:32:14 PM"
        },
        {
            "datas_line": [
                "154",
                "156",
                "155",
                "155",
                "155",
                "156",
                "158",
                "159",
                "158",
                "157",
                "157",
                "156",
                "157",
                "158",
                "159",
                "158",
                "158",
                "159",
                "159",
                "159",
                "158",
                "159",
                "159",
                "156",
                "159",
                "157",
                "158",
                "156"
            ],
            "log_time": "5/18/2017 4:34:14 PM"
        },
        {
            "datas_line": [
                "154",
                "156",
                "155",
                "155",
                "155",
                "156",
                "158",
                "159",
                "158",
                "157",
                "157",
                "156",
                "157",
                "158",
                "159",
                "158",
                "158",
                "159",
                "159",
                "159",
                "158",
                "159",
                "159",
                "156",
                "159",
                "157",
                "158",
                "156"
            ],
            "log_time": "5/18/2017 4:34:14 PM"
        }
    ]
}]
}     

Если вы видите любую другую ошибку, пожалуйста, дайте мне знать, что я могу это исправить.

1 Ответ

0 голосов
/ 28 мая 2018

У вас здесь есть несколько ошибок:

1) Удалите new Date в функции contextArea генератора области и измените d.log_time на d.date:

var contextArea = d3.svg.area()
       .interpolate("monotone")
       .x(function(d) {
          return xScale2(parseTime(d.date));
       })
       .y0(height2)
       .y1(0);

2) В функции генератора строк вам необходимо сначала проанализировать дату для атрибута x:

var line = d3.svg.line()
  .interpolate("basis")
  .x(function(d) {
    return xScale(parseTime(d.date)); // Parse to date object 
  })
  .y(function(d) {
    return yScale(d.temperature);
  })
  .defined(function(d) {
    return d.temperature;
  });

Вот ваш Плункер

...