若条件从未满足,因此我在一个简单条形图中的条形图总是蓝色的,而对于低于某个数字的值,我希望它们是红色的



我一直在尝试使用此代码创建具有给定数据的条形图。它有效,但从不返回红色,而是始终返回蓝色。我试过把b[I]>0,仍然只有蓝色条。参数为b的函数肯定会执行,我也尝试过(b,I(。

<!DOCTYPE html>
<html>
<head>
<script src = "https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<svg height = "250px" width="500px"></svg>
<script>
var b = [5,9,6,4,3]; 
var x = 100; 
const height = 250; 
for(var i=0; i<b.length;i++)
{
var svg = d3.select("svg").data(b).append("rect").attr("x",x)
.attr("y",height - (b[i]*20))
.attr("width",20).attr("height", b[i]*20).attr("fill", function(b){
if(b[i]<6) //This if condition never gets checked and hence doesn't work
{
return "red";
}
else
{
return "blue"; //This executes
}
})
x = x + 25; //Increment for the position of next bar
}
</script>
</body>
</html>

您制作了一个阴影变量b作为回调的参数,因此它不是一个数组,而是它的项。由于您使用循环分别绘制每个点,因此可以避免使用回调。所以不是

.attr("fill", function(b) { ... })

你需要写这个

.attr("fill", b[i] < 6 ? "red" : "blue")

顺便说一句,d3-js可以为你迭代点:

<script>
var b = [5, 9, 6, 4, 3];
var xOffset = 100;
const height = 250;
var svg = d3.select("svg")
.selectAll('rect')
.data(b)
.enter()
.append('rect')
.attr("x", (d, i) => xOffset + 25 * i)
.attr("y", d => height - d * 20)
.attr("width", 20)
.attr("height", d => d * 20)
.attr("fill", d => d < 6 ? "red" : "blue");
</script>

最新更新