Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3: How to add border to a circle on an if-condition?

I am adding few circles to my d3 graph as below:

 this.node = this.svg.append('g')
    .attr('class', 'nodes')
  .selectAll('circle')
  .data(graph.nodes)
  .enter().append('circle')
    .attr('r', 5)
    .attr('fill', (d) => { return this.color(d.group); })
    .on('click', this.mouseclick)
    .call(d3.drag()
        .on('start', this.dragstarted)
        .on('drag', this.dragged)
        .on('end', this.dragended));

Just like d.group used above, I have d.error present in my data which an either be true or false. How can I show a red border for the same node while its being appended (or later?) if d.error === true?

like image 251
Usman Avatar asked Jul 04 '18 08:07

Usman


1 Answers

You can use a condition on this d.error and apply a transparent stroke if it's false and red otherwise:

.style("stroke", d => d.error ? "red" : "transparent")

Using undefined instead of transparent also does the trick:

.style("stroke", d => d.error ? "red" : undefined)
// which can also be written:
.style("stroke", d => { if (d.error) return  "red" })

Here is a demo:

d3.select("svg").attr("width", 500).attr("height", 500)
  .selectAll("circle")
  .data([{ x: 85, y: 80, r: 35, error: true }, { x: 265, y: 124, r: 45, error: false }])
  .enter().append("circle")
    .attr("transform", d => "translate(" + d.x + "," + d.y + ")")
    .attr("r", d => d.r)
    .style("fill", "blue")
    .style("stroke", d => d.error ? "red" : "transparent");
  
<script src='https://d3js.org/d3.v5.js' charset='utf-8'></script>
<svg></svg>
like image 195
Xavier Guihot Avatar answered Sep 18 '22 13:09

Xavier Guihot