I know this question have been asked multiple times on SO. I tried some of those answers but It didn't worked. What is the best way to center the svg element inside div
<html>
<head>
<script src=".v3.min.js" ></script>
</head>
<body>
<div id='canvas'></div>
<script>
var data = [10, 50, 80];
var r = 300;
var color = d3.scale.ordinal()
.range(['red', 'blue', 'orange']);
var canvas = d3.select('#canvas').append('svg')
.attr('width', 700)
.attr('height', 600);
var group = canvas.append('g')
.attr('transform', 'translate(300, 300)');
var arc = d3.svg.arc()
.innerRadius(200)
.outerRadius(r);
var pie = d3.layout.pie()
.value(function (d) {
return d;
});
var arcs = group.selectAll('.arc')
.data(pie(data))
.enter()
.append('g')
.attr('class', 'arc');
arcs.append('path')
.attr('d', arc)
.attr('fill', function (d) {
return color(d.data);
});
arcs.append('text')
.attr('transform', function (d) {
return 'translate(' + arc.centroid(d) + ')';
})
.attr('text-anchor', 'middle')
.attr('font-size', '1.5em')
.text(function (d) {
return d.data;
});
</script>
</body>
</html>
I want to put the donut chart in center
D3 Donut Chart
I know this question have been asked multiple times on SO. I tried some of those answers but It didn't worked. What is the best way to center the svg element inside div
<html>
<head>
<script src="http://d3js/d3.v3.min.js" ></script>
</head>
<body>
<div id='canvas'></div>
<script>
var data = [10, 50, 80];
var r = 300;
var color = d3.scale.ordinal()
.range(['red', 'blue', 'orange']);
var canvas = d3.select('#canvas').append('svg')
.attr('width', 700)
.attr('height', 600);
var group = canvas.append('g')
.attr('transform', 'translate(300, 300)');
var arc = d3.svg.arc()
.innerRadius(200)
.outerRadius(r);
var pie = d3.layout.pie()
.value(function (d) {
return d;
});
var arcs = group.selectAll('.arc')
.data(pie(data))
.enter()
.append('g')
.attr('class', 'arc');
arcs.append('path')
.attr('d', arc)
.attr('fill', function (d) {
return color(d.data);
});
arcs.append('text')
.attr('transform', function (d) {
return 'translate(' + arc.centroid(d) + ')';
})
.attr('text-anchor', 'middle')
.attr('font-size', '1.5em')
.text(function (d) {
return d.data;
});
</script>
</body>
</html>
I want to put the donut chart in center
D3 Donut Chart
Share Improve this question asked Dec 5, 2015 at 5:57 Mahtab AlamMahtab Alam 1,8703 gold badges23 silver badges42 bronze badges 1- What did you try and how did it not work? – Lars Kotthoff Commented Dec 5, 2015 at 6:05
2 Answers
Reset to default 12You can add couple of css lines to the SVG element. You can inline it or have it in a separate style sheet. Just make sure it loads.
svg{
display: block;
margin: auto;
}
This will align the SVG to the center of the div.
Just add centering style to your div.
<div id='canvas' style="text-align:center;"></div>
It will work.