仅当折线图具有相关注释时才在折线图中添加圆

时间:2018-06-26 23:50:56

标签: javascript d3.js charts

我创建了一个漂亮的折线图,在每个数据点上都带有圆圈:jsfiddle

我的问题是圆圈,只有在数据点上有“注释”时才让它们显示。

svg.append("path")
        .data([data])
        .attr("class", "line")
        .attr("stroke", "#6b38df")
        .attr("d", valueline);

    svg.append("g").selectAll("circle")
        .data(data)
        .enter()
        .append("circle")
        .attr("r", 4)
        .attr("cx", function(d) {
            return x(d.date)
        })
        .attr("cy", function(d) {
            return y(d.close)
        })
        .attr("fill", "none")
        .attr("stroke", "#BA85FF")
        ;

    svg.append("g").selectAll("text")
        .data(data)
        .enter()
        .append("text")
        .attr("x", function(d) {
            return x(d.date) - paddingForText
        })
        .attr("y", function(d) {
            return y(d.close) + paddingForText
        })
        //.attr("fill", "white")
        .text(function(d) {
            return d.notes
        })
        .classed("notepoint", true)
        .style("font-family", "Roboto")
        .style("font-size", "14px")
        ;

在上面的代码中,我将“注释”作为标签显示在圆上,但是我只想将该数据点插入圆上以显示是否有注释。我想这样做是因为当图表上的圆圈过多时,它会变得很拥挤且难以阅读。

仅当数据点上有注释时,我才能显示圆圈吗?

1 个答案:

答案 0 :(得分:2)

在您的圈子选择中,根据notes属性过滤数据:

.data(data.filter(function(d){
    return d.notes
}))

这是更新的JSFiddle:http://jsfiddle.net/cerj7s16/1/