Gangrel
Gangrel

Reputation: 481

Centering svg image used on clustered bar chart

I have appended an SVG image to my clustered bar chart but need the image to sit in the centre of the two values. Currently it's sitting underneath the first value only.

Here is my fiddle Any ideas how this can be done? I know I could probably fudge but using +30 for example in the x attribute but ideally there's just a way I can force it to sit centrally.

svg.selectAll(".images")
      .data(data)
      .enter().append("g")
      .attr("class", "g")
      .attr("transform", function(d) { return "translate(" + (x0(d.xx)) + ",0)"; })

      .selectAll("rect")
      .data(function(d) { return d.dataNew; })
        .enter()
      .append("svg:image")

       .attr("x", function(d) { return x1(d.xx )  } )
        .attr("y", height + margin.bottom-40)
        .attr("width", x1.rangeBand())
        .attr("height", 40)
       .attr("xlink:href", function(d){return "http://pngimg.com/uploads/football/football_PNG52789football_PNG52789.png"})

Upvotes: 2

Views: 78

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102188

The math you need is:

.attr("transform", function(d) {
    return "translate(" + (x0(d.xx) + (x0.rangeBand() - x1.rangeBand()) / 2) + ",0)";
})

Here is your JSFiddle with that change: https://jsfiddle.net/4bsvr6y2/

Upvotes: 2

Related Questions