@herminia_bruen
To center a title over an SVG chart using d3.js, you can follow these steps:
1 2 3 4 |
var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); |
1 2 |
var chartGroup = svg.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); |
1 2 3 4 5 6 |
var title = chartGroup.append("text") .attr("class", "title") .attr("x", width / 2) // Set x position to half of the width .attr("y", 0) .attr("text-anchor", "middle") // Align text to the center .text("Chart Title"); |
Here's a complete example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<!DOCTYPE html> <html> <head> <title>Center Title over SVG Chart with d3.js</title> <style> .title { font-size: 20px; fill: #333; } </style> </head> <body> <script src="https://d3js.org/d3.v7.min.js"></script> <script> var width = 500; var height = 300; var margin = { top: 20, right: 20, bottom: 30, left: 50 }; var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); var chartGroup = svg.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var title = chartGroup.append("text") .attr("class", "title") .attr("x", width / 2) .attr("y", 0) .attr("text-anchor", "middle") .text("Chart Title"); </script> </body> </html> |
Make sure to adjust the values of width
, height
, and margin
to fit your chart dimensions.