在D3中指定可缩放热力图的视图

5
我正在制作一个带有缩放和平移功能的热力图,并发现在缩放和平移时,数据点会出现在y轴左侧,这是因为我增加了热力图左侧的空间,以便为y轴腾出空间(请查看图片)。我应该怎么避免这种情况发生?以下提供了代码示例。
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) + ")"; });
2个回答

1

我发现解决方案是创建一个剪辑路径。我使用了这个示例中的剪辑方法: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 + ")");

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接