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
?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With