2015-04-22 57 views
5

我正在做一个具有缩放和平移功能的热图,并且当我将空间增加到缩放和平移时,意识到数据点在缩放和平移时显示在y轴的左侧热图的左侧,以便为y轴创造空间(见图片)。我怎样才能避免这种情况?代码示例在下面提供。在D3中指定可缩放热图的视图

enter image description here

var zoom = d3.behavior.zoom() 
    .scaleExtent([dotWidth, dotHeight]) 
    .x(xScale) 
    .on("zoom", zoomHandler); 

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

function zoomHandler() { 
    var t = zoom.translate(), 
     tx = t[0], 
     ty = t[1]; 

    tx = Math.min(tx, 0); // tx < 0 
    tx = Math.max(tx, -1000); // 
    zoom.translate([tx, ty]); 

    svg.select(".x.axis").call(xAxis); 
    svg.selectAll("ellipse") 
     .attr("cx", function(d) { return xScale(d.day); }) 
     .attr("cy", function(d) { return yScale(d.hour); }) 
     .attr("rx", function(d) { return (dotWidth * d3.event.scale); }); 
} 

svg.selectAll("ellipse") 
    .data(dataset) 
    .enter() 
    .append("ellipse") 
    .attr("cx", function(d) { return xScale(d.day); }) 
    .attr("cy", function(d) { return yScale(d.hour); }) 
    .attr("rx", dotWidth) 
    .attr("ry", dotHeight) 
    .attr("fill", function(d) { return "rgba(100, 200, 200, " + colorScale(d.tOutC) + ")"; }); 

回答

0

我想出的是,解决方案是创建剪切路径。我使用这个例子中的剪辑方法:http://bl.ocks.org/mbostock/4248145。基本上我加了下面的代码:

svg.append("clipPath") 
    .attr("id", "clip") 
    .append("rect") 
    .attr("class", "mesh") 
    .attr("width", width) 
    .attr("height", height); 

svg.append("g") 
    .attr("clip-path", "url(#clip)") 
    .selectAll(".hexagon") 
    .data(hexbin(points)) 
    .enter().append("path") 
    .attr("class", "hexagon") 
    .attr("d", hexbin.hexagon()) 
    .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }) 
    .style("fill", function(d) { return color(d.length); }); 

该代码也可以正常工作以及缩放功能。只需在创建svg画布时调用缩放功能。像这样:

// SVG canvas 
var svg = d3.select("#chart") 
    .append("svg") 
    .attr("width", width + margin.left + margin.right) 
    .attr("height", height + margin.top + margin.bottom) 
    .call(zoom) 
    .append("g") 
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");