D3 - 如果数据中的列存在,则更改格式

时间:2018-03-28 16:11:26

标签: javascript css d3.js formatting

我有一个json去D3:

{"time": "foo1", "values1": "bar1", "values2": "val1"}
{"time": "foo2", "values1": "bar2", "values2": "NULL"}
{"time": "foo3", "values1": "bar3", "values2": "val2"}
{"time": "foo4", "values1": "bar4", "values2": "NULL"}

它生成values1time的线图,其上带有圆形点,由此生成:

var circles = svg.selectAll("circle")
                .data(data);
            circles.exit().remove();
            circles.enter().append("circle")
               .attr("r", 2)
               .merge(circles)
               .attr("cx", function(d) { return x(d.time); })
               .attr("cy", function(d) { return y(d.values1); });

然后有一些CSS来定义圆圈的颜色。一切正常。

如果来自同一时间戳的values2不是NULL,是否可以使用不同颜色的圆圈? 例如,从第一行数据开始,一个点位于(foo1,bar1),并且为黑色,因为values2不为空,而从下面一行开始,该点将在{{ 1}},并且为红色,因为(foo2,bar2)为空。

也许两组独立的圈子是合适的,这似乎是最明显的解决方案,但我仍然不确定如何实施这一条件。

1 个答案:

答案 0 :(得分:0)

添加: .style("fill", function(d){ return d.values2 === "NULL" ? "red" : "black"})。回答@GerardoFurtado的信用