问题描述
我试图通过一个饼图示例来使图表的位置在其包含元素的内部居中对齐,在这种情况下,只是将一个简单的div设置为使用100%可用宽度.
请参见小提琴
您可以看到图表的中心位于div的左上角,而不是按照我设置的transform属性使用可用宽度和高度的中心点:
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
我正在按照此示例此处,它使用硬代码宽度,在本例中,我将使其响应并在屏幕调整大小事件上重新绘制.
为了防止从div \ svg区域的中心点绘制图表,我在做错什么或完全错过了?
编辑
好的,通过检查DOM,我注意到形成每个饼图段的路径不是svg group(g)元素的子级,而在其他示例中,我看到了.我不确定为什么在我的情况下无法正常工作,但这似乎是我所知道的问题
您是正确的,您希望饼图元素是<g>
的子元素.为此,首先将<g>
存储在这样的变量中:
var g = svg.attr('height', height)
.append('g')
.attr('transform', 'translate(' + width/2 + ',' + height/2 +')');
然后将<path>
创建为g
的子代:
var path = g.selectAll("path")
.data(pie(dataset.apples))
.enter().append("path")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc);
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
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);
这篇关于将svg上的饼形图居中对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!