Reputation: 481
I have created a simple KPI box using d3. Currently the icon and %value are static but I want them attached to the end of large KPI number so that it prevents the elements from overlapping.
eg No issues with a small number
However, with a large number the overlap happens
How can I append the icon and %value to the end if the KPI value?
script:
var tile = svg.append("g").attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
//add rect
tile.append("rect")
.attr('class', 'rect')
.attr("rx",5 )
.attr("ry", 5)
.attr("x",0 )
.attr("y", -35)
.attr("width", width)
.attr("height", height)
//add Large KPI Number
tile.append("text")
.data(data)
.attr('class', 'labelx')
.attr("text-anchor", "middle")
.attr("x", width / 2.5)
.attr("y", 150)
.text(function(d) {
return formatComma(d.Value)
})
//add % variance
tile.append("text")
.data(data)
.attr('class', 'var')
.attr("text-anchor", "middle")
.attr("x", width / 1.4)
.attr("y", 130)
.text( function(d) {
return formatPC(d.Var) })
//add icon
tile.selectAll(".image")
.data(data)
.enter()
.append("svg:image")
.attr("x", width / 1.5)
.attr('class', 'icon glowed')
.attr("y", 50)
.attr("width", 50)
.attr("height", 50)
.attr("xlink:href", function(d) {
if (d.Var < 0 ) {
return "https://upload.wikimedia.org/wikipedia/commons/thumb/0/04/Red_Arrow_Down.svg/2048px-Red_Arrow_Down.svg.png"
} else {
return "https://upload.wikimedia.org/wikipedia/commons/thumb/5/50/Green_Arrow_Up.svg/1200px-Green_Arrow_Up.svg.png"
}
})
Upvotes: 0
Views: 255
Reputation: 3402
You could use getBBox
to determine the width of each text block after plotting, but the simpler solution would be changing the anchoring:
tile.append("text")
.data(data)
.attr('class', 'labelx')
.attr("text-anchor", "end") // position the end of the text here
.attr("x", width / 2.5)
.attr("y", 150)
.text(function(d) {
return formatComma(d.Value)
})
//add % variance
tile.append("text")
.data(data)
.attr('class', 'var')
.attr("text-anchor", "start") // position the start of the var at the same spot
.attr("x", width / 2.5)
.attr("y", 130)
.text( function(d) {
return formatPC(d.Var) })
Upvotes: 1