【发布时间】:2014-05-27 18:43:19
【问题描述】:
我正在尝试使用两个下拉菜单制作 d3 散点图。下拉菜单用于选择要相互绘制的数据集。我使用两个全局变量来跟踪当前使用的数据集。 “currentX”是第一个数据集的名称(在 x 轴上),“currentY”是第二个数据集的名称。
我的比例函数取决于“currentX”和“currentY”的值。这是我的 xScale 函数的示例:
var xScale = d3.scale.linear()
.domain([d3.min(dataset, function(d){return d.data[currentX]}), d3.max(dataset, function(d){return d.data[currentX]})
.range([padding, w - padding])
.nice();
我的 yScale 函数是相同的,但使用 currentY 而不是 currentX。我的问题是,当我尝试更改数据视图时,我的比例不会更新。这是在数据视图之间切换的代码:
d3.selectAll('select')
.on('change', function() {
// Update currentX and currentY with the currently selected datasets
key = Object.keys(dataset[0].data)[this.selectedIndex];
if (this.getAttribute('id') == 'xSelect') {currentX = key}
if (this.getAttribute('id') == 'ySelect') {currentY = key}
// Change data used in the scatterplot
svg.selectAll('circle')
.data(dataset)
.transition()
.duration(1000)
.attr('cx', function(d) { return xScale(d.data[currentX]) })
.attr('cy', function(d) { return yScale(d.data[currentY]) })
.attr('r', 2)
};
我希望更新 xScale 和 yScale 函数,以反映 currentX 和 currentY 的新值。但由于某种原因,这些功能没有更新。如果有人能帮我解决这个问题,我将不胜感激!谢谢!
更新:澄清一下,我的问题是我的 xScale 和 yScale 函数没有改变,即使 xCurrent 和 yCurrent(以及它们的最小值和最大值)已经改变。例如,“console.log(xScale(-5))”总是产生相同的值。这个值应该随着 xCurrent 和 yCurrent 的变化而变化!再次感谢。
更新 2:全局变量“xCurrent”和“yCurrent”正在更新。此外,如果我在 .on('change') 函数中定义了新的 xScale 和 yScale 函数,那么我的比例就会更新。这实际上解决了我的问题,但我仍然想知道为什么我不能这样做。还在努力学习 D3!
【问题讨论】:
标签: javascript d3.js scale