Как реализовать привязку кисти в многосерийной линейной диаграмме? - PullRequest
0 голосов
/ 25 мая 2018

, поэтому я пытаюсь реализовать в моем графике кисть, как в этом примере: http://bl.ocks.org/DStruths/9c042e3a6b66048b5bd4

Но у меня возникают некоторые проблемы с настройкой contextArea. Я думаю, что в примере используется версия d3.v3и я нахожусь в d3.v4. С этой стороны может быть проблема.

Не могли бы вы помочь мне с этим?Я определил часть слайдера в своем коде.

Хочу заметить, что моя программа работает без части слайдера.

<svg width="960" height="500"></svg>
<script>

    var svg = d3.select("svg"),
        margin = {top: 20, right: 200, bottom: 100, left: 50},
        margin2 = { top: 430, right: 10, bottom: 20, left: 40 },
        width = svg.attr("width") - margin.left - margin.right,
        height = svg.attr("height") - margin.top - margin.bottom,
        height2 = svg.attr("height") - margin2.top - margin2.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var parseTime = d3.timeParse("%m/%d/%Y %H:%M:%S %p");

    var x = d3.scaleTime().range([0, width]),
        x2 = d3.scaleTime().range([0, width]), // Duplicate xScale for brushing ref later
        y = d3.scaleLinear().range([height, 0]),
        z = d3.scaleOrdinal(d3.schemeCategory10);

    var maxY; // Defined later to update yAxis  

    var line = d3.line()
        .curve(d3.curveBasis)
        .x(function(d) { return x(parseTime(d.date)); })
        .y(function(d) { return y(d.temperature); });

    //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
    g.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]
                    };
                })
            } 
        });
        console.log(responses);

        x.domain(d3.extent(responses, function(d) { return parseTime(d.log_time); }));

        x2.domain(x.domain()); // Setting a duplicate xdomain for brushing reference later

        y.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; }); })
        ]);

        z.domain(temp_list.map(function(c) { return c.id; }));


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

        var brush = d3.brushX() //for slider bar at the bottom
            .extent(responses, function(d) { return parseTime(d.log_time); })
            .on("brush", brushed);

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

          // HOW TO SET CONTEXTE AREA ??? 
          var contextArea = d3.area() // Set attributes for area chart in brushing context graph
            .interpolate("monotone")
            .x(function(d) { return xScale2(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(responses[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-------------------------------------------------------------------------------

        g.append("g")
            .attr("class", "axis axis--x")
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x));

        g.append("g")
              .attr("class", "axis axis--y")
              .call(d3.axisLeft(y))
            .append("text")
              .attr("transform", "rotate(-90)")
              .attr("y", 6)
              .attr("dy", "0.71em")
              .attr("fill", "#000")
              .text("Temperature, ยบC");

        var temp = g.selectAll(".temp")
            .data(temp_list)
            .enter().append("g")
            .attr("class", "temp");

        temp.append("path")
            .attr("class", "line")
            .attr("d", function(d) { return line(d.values); })
            .style("stroke", function(d) { return z(d.id); });

        temp.append("text")
            .datum(function(d) { return {id: d.id, value: d.values[d.values.length - 1]}; })
            .attr("transform", function(d) { return "translate(" + x(parseTime(d.value.date)) + "," + y(d.value.temperature) + ")"; })
            .attr("x", 3)
            .attr("dy", "0.35em")
            .style("font", "10px sans-serif")
            .text(function(d) { return d.id; });

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

            x.domain(brush.empty() ? x2.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(responses); // Find max Y rating value categories data with "visible"; true
            y.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(y);   

            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
              });

        };      

    });
</script>

Данные используются для проверки:

{
    "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"
            }
        ]
    }]
} 

О, я также заметил, что моя ось х не отображается правильно.Если у кого-то есть ответ на этот вопрос, я тоже возьму его ^^ 'enter image description here

...