2016-12-11 53 views
1

我在D3.js v4上有一个热图,我试图给它增加缩放和平移功能。缩放只能在x轴上工作,并不会改变y轴。有关缩放部分低于:在D3.js/v4中放大热图重绘

var x = d3.scaleTime().range([0, width]).domain([minDate, maxDate]); 
var xAxis = d3.axisBottom().scale(x); 
var zoom = d3.zoom().scaleExtent([1, 2]) 
      .translateExtent([[80, 20], [width, height]]) 
      .on("zoom", zoomed); 

svg.call(zoom); 

function zoomed() { 
    xAxis.scale(d3.event.transform.rescaleX(x)); 
    svg.select(".x.axis").call(xAxis); 
    update(); 
} 

function update() { 
    svg.selectAll(".cell") 
     .attr('clip-path', 'url(#plotAreaClip)') 
     .attr("x", function (d) { return x(d.timestamp); }) 
     .attr("y", function (d) { return y(d.hour); }) 
     .attr("width", function (d) { return x(d3.timeWeek.offset(d.timestamp, 1)) - x(d.timestamp); }) 
     .attr("height", function (d) { return y(d.hour + 1) - y(d.hour); }) 
     .attr("fill", function (d) { return colorScale(d.value); }); 
} 

当我真正在zoomed()功能注释掉update(),我可以看到,轴/出来就好放大。但是当update()在函数中时,它只会删除图表中的所有矩形。

JS小提琴链接是https://jsfiddle.net/7z1f4c5p/(我不知道上传csv文件到JSFiddle的方法,所以我不得不把整个数据写到JS部分,对不起,代码在底部。第97行,变焦将无法正常工作。

+0

小提琴缺少代码 –

回答

1

你需要在你的update()应用新的刻度值。

function update() { 
    // update: cache rescaleX value 
    var rescaleX = d3.event.transform.rescaleX(x); 
    svg.selectAll(".cell").attr('clip-path', 'url(#plotAreaClip)') 
     // update: apply rescaleX value 
     .attr("x", function(d) { 
      return rescaleX(d.timestamp); 
     }).attr("y", function(d) { 
      return y(d.hour); 
     }) 
     // update: apply rescaleX value 
     .attr("width", function(d) { 
      return rescaleX(d3.timeWeek.offset(d.timestamp, 1)) - rescaleX(d.timestamp); 
     }).attr("height", function(d) { 
      return y(d.hour + 1) - y(d.hour); 
     }).attr("fill", function(d) { 
      return colorScale(d.value); 
     }); 
} 

看起来像在clipPathrect没有widthheight

// update: set widht and height of clippath rect 
plotArea.append("clipPath") 
    .attr("id", "plotAreaClip") 
    .append("rect") 
    .attr('width', width) 
    .attr('height', height); 
    //.attr({width: width, height: height}); 

这里的工作小提琴 - https://jsfiddle.net/7z1f4c5p/2/

您需要调整图的左边和右边的空间。看起来像缩放时有点关闭。

+0

谢谢。是否也可以使用'var rescaleX = d3.event.transform.rescaleX(x).clamp(true);'而不是'clipPath'?它为我工作,但我想确定。 – nope

+0

在视觉上它们可能看起来很相似。区别在于'clamp(true)'标尺的输出被强制在范围内,在你的情况下'[0,width]'。如果使用clipPath,则输出将按原样进行缩放。 clipPath之外的任何内容都将不可见。简单的方法来看看这是检查图中第一个矩形的元素。通过'clamp(true)',矩形x是'0'。使用'clipPath',而不应用'clamp(true)',x位置为负值,因为它位于'clipPath'区域之外并且在缩放范围之外,所以它将不可见。 – phoa