我正在尝试随着基础数据的更改使用过渡来更新堆积的条形图。每次都调用相同的“渲染”函数,并且在不涉及任何过渡的情况下都能很好地工作。但是,我想动画化值的变化,从当前状态过渡到下一个状态。
我已经解决了一些问题,但是感觉我的解决方案很笨拙-希望有更好的方法来处理堆积的条形图。
我的方法是执行以下操作:
使用上述方法,如果prevData具有值,则使用这些值设置初始条件。我的问题是查找和设置初始条件确实很麻烦:
if (prevData.length > 0) {
//get the parent key so we know who's data we are now updating
var devKey = d3.select(this.parentNode).datum().key;
//find the data associated with its PREVIOUS value
var seriesData = seriesPrevData.find(function (s) { return (s.key == devKey); })
if (seriesData != null) {
//now find the date we are currently looking at
var day = seriesData.find(function (element) { return (element.data.Date.getTime() == d.data.Date.getTime()); });
if (day != null) {
//now set the value appropriately
//console.debug("prev height:" + devKey + ":" + day[1]);
return (y(day[0]) - y(day[1]));
}
}
}
我正在做的是查找正确的键数组(由d3.stack()创建),然后尝试查找适当的先前数据条目(如果存在)。但是,搜索父节点并遍历数组以找到所需的键和适当的数据元素感觉很漫长。
因此,我的问题是,是否有更好的方法可以做到这一点?或部分?
很抱歉,对于冗长的帖子,我花了整整一天的时间来制定解决方案,但由于我真正需要的只是项目的先前值而感到沮丧。必须做所有这些“体操”来获得我所需要的东西,似乎非常“不” D3.js,如:-)
谢谢
以下是一个动画条形图的简单示例。它将遍历数据集的两个不同版本,以展示如何使用d3非常轻松地处理基础数据中的更改。在此示例中,无需为过渡/动画进行任何手动数据准备。
var data = [
[1, 2, 3, 4, 5],
[1, 6, 5, 3]
];
var c = d3.select('#canvas');
var currentDataIndex = -1;
function updateData() {
// change the current data
currentDataIndex = ++currentDataIndex % data.length;
console.info('updating data, index:', currentDataIndex);
var currentData = data[currentDataIndex];
// get our elements and bind the current data to it
var rects = c.selectAll('div.rect').data(currentData);
// remove old items
rects.exit()
.transition()
.style('opacity', 0)
.remove();
// add new items and define their appearance
rects.enter()
.append('div')
.attr('class', 'rect')
.style('width', '0px');
// change new and existing items
rects
// will transition from the previous width to the current one
// for new items, they will transition from 0px to the current value
.transition()
.duration('1000')
.ease('circle')
.style('width', function (d) { return d * 50 + 'px'; });
}
// initially set the data
updateData();
// keep changing the data every 2 seconds
window.setInterval(updateData, 2000);
div.rect {
height: 40px;
background-color: red;
}
div#canvas {
padding: 20px;
border: 1px solid #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="canvas">
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句