Javascript d3点击按钮时在线更新圆圈
我有一个图表,当点击按钮时,它应该会更新图表中的数据外观 这是一把小提琴: 不知何故,按钮点击在小提琴中不起作用,但在我的源代码中起作用 以下是图表的图像 单击按钮之前: 单击按钮后: 因此直线和轴也会被更新。但是,线条上的点如何移动到新的位置并消失呢 以下是更新方法对点的作用方式:Javascript d3点击按钮时在线更新圆圈,javascript,d3.js,charts,Javascript,D3.js,Charts,我有一个图表,当点击按钮时,它应该会更新图表中的数据外观 这是一把小提琴: 不知何故,按钮点击在小提琴中不起作用,但在我的源代码中起作用 以下是图表的图像 单击按钮之前: 单击按钮后: 因此直线和轴也会被更新。但是,线条上的点如何移动到新的位置并消失呢 以下是更新方法对点的作用方式: function weekData() { var arr = getDataArr(weekString); // Get the data again var data =
function weekData() {
var arr = getDataArr(weekString);
// Get the data again
var data = arr.map(function(d) {
return {
date: parseDate(d[0]),
ideal: d[3],
open: d[1]
};
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain([0, d3.max(data, function(d) {
return Math.max(d.open);
})]);
xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(arr.length - 1)
.tickFormat(d3.time.format("%Y-%m-%d"));
// Select the section we want to apply our changes to
var svg = d3.select("#area").transition();
// Make the changes
svg.select(".openLine") // change the line
.duration(750)
.attr("d", openLine(data))
svg.select(".dot")
.duration(750)
.attr("r", 3.5)
.style("fill", function(d) {
if (d.open <= d.ideal) {
return "#579FAD"
} else {
return "#AD6557"
};
})
.attr("cx", function(d){
return x(d.date);
})
.attr("cy", function(d){
return y(d.open);
})
svg.select(".x.axis") // change the x axis
.duration(750)
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", ".15em")
.attr("transform", function(d) {
return "rotate(-65)"
});
svg.select(".y.axis") // change the y axis
.duration(750)
.call(yAxis)
}
函数weekData(){
var arr=getDataArr(周字符串);
//再次获取数据
var数据=arr.map(功能(d){
返回{
日期:解析日期(d[0]),
理想:d[3],
开放:d[1]
};
});
//缩放数据的范围
x、 域(d3)。范围(数据,函数(d){
返回日期;
}));
y、 域([0,d3.max(数据,函数(d)){
返回Math.max(d.open);
})]);
xAxis=d3.svg.axis()
.比例(x)
.orient(“底部”)
.刻度(arr.length-1)
.tickFormat(d3.time.format(“%Y-%m-%d”);
//选择要应用更改的节
var svg=d3.select(“#area”).transition();
//做出改变
svg.select(“.openLine”)//更改行
.持续时间(750)
.attr(“d”,openLine(数据))
svg.select(“.dot”)
.持续时间(750)
.attr(“r”,3.5)
.样式(“填充”,功能(d){
如果(d.open这把小提琴符合你的要求,我想:
我对您的代码做了3个更改:
首先,您试图通过按钮onclick
调用的函数超出了范围
<input name="weekButton" type="button" value="1 week" onclick="weekData()" />
其次,在添加点之前,您正在为点设置类名“dot”
svg.selectAll(".dot")
.data(data)
.attr("class", "dot")
.enter().append("circle")
这意味着没有实际设置类名(因此意味着以后不能使用类名来选择要更新的点)。在append
之后设置class
属性就可以了
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
最后,在更新功能中(单击按钮后),您只选择了第一个点:
这应该是:
svg.selectAll(".dot")
要确保所有点都被更新请查看enter&exit function()
:上面写着“svg.selectAll(…)。数据不是函数”,这是我不明白的另一件事。说到这里,我仍然建议查看一般的更新模式(enter/update/exit)作为一种更好的代码结构。谢谢!我在网上搜索了很多,但找不到合适的解决方案。我将阅读这段代码,并尝试制作更多类似d3的代码。
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
svg.select(".dot")
svg.selectAll(".dot")