mindparse
mindparse

Reputation: 7315

Center align a pie chart on svg

I am trying to get a pie chart example to work whereby the position of the chart is centre aligned inside it's containing element, just a simple div in this case set to use 100% width available.

See this fiddle

As you can see the centre of the chart is positioned in the top left corner of the div, rather than using the centre point of the available width and height as per the transform attribute I am setting:

.attr('transform', 'translate(' + width / 2 +  ',' + height / 2 + ')');

I am following this example here, which uses a hard code width, in my case I am going to end up making it responsive and re-draw on screen resize events.

What am I doing wrong, or missed out altogether, to prevent the chart from being drawn from the centre point of the div\svg area?

EDIT

OK, from inspecting the DOM I notice the path's that form each of the pie segments are not children of the svg group (g) element, whereas in other examples I have seen they are. I'm not sure why this is not working correctly in my case, but that seems to be the issue from what I can tell

Upvotes: 3

Views: 5311

Answers (1)

mdml
mdml

Reputation: 22922

You're right that you want your pie chart elements to be children of the <g>. To do that, first store the <g> in a variable like so:

var g = svg.attr('height', height)
        .append('g')
        .attr('transform', 'translate(' + width/2 +  ',' + height/2 +')');

Then create the <path>s as children of g:

var path = g.selectAll("path")
    .data(pie(dataset.apples))
    .enter().append("path")
    .attr("fill", function(d, i) { return color(i); })
    .attr("d", arc);

Upvotes: 5

Related Questions