应用放大矩阵散点图d3.js v4

时间:2018-04-20 23:59:42

标签: javascript d3.js

这是d3 V4中矩阵散点图的一个plunkr http://plnkr.co/edit/7meh4sMhxItcQtCaAtZP?p=preview (加载和显示可能需要一些时间)

我期待放大情节,以方便的方式看到杂乱的点。 我使用d3.zoom()来重新缩放轴,但没有相应地绘制圆圈。

以下是问题描述: 最初,所有轴都设置了不同的范围(如顶部y轴的范围为4.5-7.5,低于y轴的范围为2.0-4.0 ..) 现在,在缩放之后(即在鼠标滚过圆圈时),所有轴都设置在相同的范围内,导致所有圆都对角定向。

是否有解决方法,以便我们可以相应地缩放轴并可以很好地显示它!

感谢。任何帮助都会受到高度赞赏。

<!DOCTYPE html>
<meta charset="utf-8">
<style>

    svg {
        font: 10px sans-serif;
        padding: 10px;
    }

    .axis,
    .frame {
        shape-rendering: crispEdges;
    }

    .axis line {
        stroke: #ddd;
    }

    .axis path {
        display: none;
    }

    .cell text {
        font-weight: bold;
        text-transform: capitalize;
    }

    .frame {
        fill: none;
        stroke: #aaa;
    }

    circle {
        fill-opacity: .7;
    }

    circle.hidden {
        fill: #ccc !important;
    }

    .extent {
        fill: #000;
        fill-opacity: .125;
        stroke: #fff;
    }

    div.tooltip {
        position: absolute;
        text-align: center;
        width: 100px;
        height: 80px;
        padding: 2px;
        font: 12px sans-serif;
        background: lightsteelblue;
        border: 0px;
        border-radius: 8px;
        pointer-events: none;
    }

</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>


<script>

  var tooltipDiv;
    d3.helper = {};

   var zoomable = true;
   var new_xScale;
   var new_yScale;


    d3.helper.tooltip = function (param1, param2) {

        var bodyNode = d3.select('body').node();


        function tooltip(selection) {
            selection.on('mouseover.tooltip', function (point) {

                // Clean up lost tooltips
                d3.select('body').selectAll('div.tooltip').remove();
                // Append tooltip
                tooltipDiv = d3.select('body')
                    .append('div')
                    .attr('class', 'tooltip');
                var absoluteMousePos = d3.mouse(bodyNode);
                //console.log('absoluteMousePos', absoluteMousePos);
                tooltipDiv
                    .style('left', (absoluteMousePos[0] + 10) + 'px')
                    .style('top', (absoluteMousePos[1] - 30) + 'px');

                var line = '';
                //var temp_key = d3.keys(point);
                var temp_key = [param1, param2];

               // _.each(d3.keys(point), function (key, index) {
                temp_key.forEach(function (key, index) {


                    if (index != temp_key.length - 1) {

                        line += key + ': ' + point[key] + '</br>';
                    } else {


                        line += key + ': ' + point[key];
                    }
                });
                tooltipDiv.html(line);
            })
                .on('mousemove.tooltip', function () {
                    // Move tooltip
                    var absoluteMousePos = d3.mouse(bodyNode);
                    tooltipDiv
                        .style("left", (absoluteMousePos[0] + 10) + 'px')
                        .style("top", absoluteMousePos[1] < 80 ? absoluteMousePos[1] + 10 :(absoluteMousePos[1] - 70) + 'px');
                })
                .on('mouseout.tooltip', function () {
                    // Remove tooltip
                    tooltipDiv.remove();
                });


        }

        tooltip.attr = function (_x) {
            if (!arguments.length) return attrs;
            attrs = _x;
            return this;
        };

        tooltip.style = function (_x) {
            if (!arguments.length) return styles;
            styles = _x;
            return this;
        };

        return tooltip;
    };

    var width = 500,
        size = 150,
        padding = 20;

    var x = d3.scaleLinear().rangeRound([padding / 2, size - padding / 2]);
    var y = d3.scaleLinear().rangeRound([size - padding / 2, padding / 2]);

    var xAxis = d3.axisBottom()
        .scale(x)
        .ticks(7);

    var yAxis = d3.axisLeft()
        .scale(y)
        .ticks(7);

    var color = d3.scaleOrdinal(d3.schemeCategory10);

    d3.json("flowers.json", function (data) {

        var attr2Domain = {},

          attrs= ['sepal length', 'sepal width', 'petal length','petal width']  
          n = attrs.length;

        attrs.forEach(function (attr) {
            attr2Domain[attr] = d3.extent(data, function (ele) {
                return ele[attr];
            });
        });

        xAxis.tickSize(size * n);
    yAxis.tickSize(-size * n);


        var svg = d3.select("body")
            .append("svg")
            .attr("width", size * n + padding)
            .attr("height", size * n + padding)
            .append("g")
            .attr("transform", "translate(" + padding + "," + padding / 2 + ")");

        svg.selectAll(".x.axis")
            .data(attrs)
            .enter().append("g")
            .attr("class", "x axis")
            .attr("transform", function (d, i) {
                return "translate(" + (n - i - 1) * size + ",0)";
            })
            .each(function (d) {
                x.domain(attr2Domain[d]);
                d3.select(this).call(xAxis);
            });

        svg.selectAll(".y.axis")
            .data(attrs)
            .enter().append("g")
            .attr("class", "y axis")
            .attr("transform", function (d, i) {
                return "translate(0," + i * size + ")";
            })
            .each(function (d) {
                y.domain(attr2Domain[d]);
                d3.select(this).call(yAxis);
            });

        var cell = svg.selectAll(".cell")
            .data(cross(attrs, attrs))
            .enter()
            .append("g")
            .attr("class", "cell")
            .attr("classx", function(d){ return d.x; })
            .attr("classy", function(d){ return d.y; })
            .attr("transform", function (d) { 
                return "translate(" + (n - d.i - 1) * size + "," + d.j * size + ")";
            });

        // Titles for the diagonal.
        cell.filter(function (d) {
            return d.i === d.j;
        })
            .append("text")
            .attr("x", padding)
            .attr("y", padding)
            .attr("dy", ".71em")
            .style("fill", "black")
            .text(function (d) {
                return d.x;
            });


        cell.each(plot);

        // plot each cell
        function plot(p) {
             cell = d3.select(this);

            x.domain(attr2Domain[p.x]);
            y.domain(attr2Domain[p.y]);

            cell.append("rect")
                .attr("class", "frame")
                .attr("x", padding / 2)
                .attr("y", padding / 2)
                .attr("width", size - padding)
                .style("pointer-events", "none")
                .attr("height", size - padding);

             var  circles = cell.selectAll("circle")
                .data(data)
                .enter().append("circle")
                .attr("cx", function (d) { 
                    return x(d[p.x]);
                })
                .attr("cy", function (d) {
                    return y(d[p.y]);
                })
                .attr("r", 4)

                //.style("fill", "green");
                .style("fill", function (d) {
                  return color(d.species);
                });




            circles.on('mousemove', function(){

            var param1 = d3.select(this.parentNode).attr("classx"); 
            var param2 = d3.select(this.parentNode).attr("classy");
            circles.call(d3.helper.tooltip(param1, param2));

            }); 


        }

//---------------------------------------------  applying zoom----------   

   applyZoom(); 

  function applyZoom() {
    if (zoomable) {
      var zoom = d3.zoom()
        .on("zoom", zoomed);

      svg.call(zoom).on("dblclick.zoom", null);
    }
  }


   function zoomed() {
   console.log('zoomed');

     new_xScale = d3.event.transform.rescaleX(x);
     new_yScale = d3.event.transform.rescaleY(y);

    console.log("new_xScale", x);

      svg.selectAll(".x.axis")
      .each(function (d) {
                x.domain(attr2Domain[d]);
                d3.select(this).call(xAxis.scale(new_xScale));
            });



       svg.selectAll(".y.axis")
      .each(function (d) {
                y.domain(attr2Domain[d]);
                d3.select(this).call(yAxis.scale(new_yScale));
            });

         cell.each(plotly);


}



 function plotly(p) {

      console.log("plotly", p);
        //return x(d[p.x])

        svg.selectAll("circle")
       .attr("cx", function (d) {
                    return new_xScale(d[p.x]);
                })
         .attr("cy", function (d) {
                   return new_yScale(d[p.y]);
                   });

        }



});


     function cross(a, b) {
        var c = [], n = a.length, m = b.length, i, j;
        for (i = 0; i < n; i++) {
            for (j = 0; j < m; j++) {
                c.push({x: a[i], i: i, y: b[j], j: j});
            }
        }
        return c;
    }

   </script>  

1 个答案:

答案 0 :(得分:0)

我认为在每个函数内的“ x.domain(attr2Domain [d])”之后移动“ new_xScale = d3.event.transform.rescaleX(x)”应该起作用。和y一样。

谢谢