Center align a pie chart on svg

ぐ巨炮叔叔 提交于 2020-01-03 19:30:59

问题


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


回答1:


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);


来源:https://stackoverflow.com/questions/34418531/center-align-a-pie-chart-on-svg

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!