Title and Axis Labels

I managed to create shortcuts for the X and Y axis. I also managed to add a title to the chart. My problem is that if I change the fields of the chart, the positions of the labels will be mixed up.

A fragment in which I change the graph fields:

var margin = {top: 60, right: 60, bottom: 60, left:120} 

Fragment in which I create labels:

  //Create Title svg.append("text") .attr("x", w / 2 ) .attr("y", 0) .style("text-anchor", "middle") .text("Title of Diagram"); //Create X axis label svg.append("text") .attr("x", w / 2 ) .attr("y", h + margin.bottom) .style("text-anchor", "middle") .text("State"); //Create Y axis label svg.append("text") .attr("transform", "rotate(-90)") .attr("y", 0-margin.left) .attr("x",0 - (h / 2)) .attr("dy", "1em") .style("text-anchor", "middle") .text("Revenue"); 

JsFiddle:
http://jsfiddle.net/u63T9/

Here is another alternative I want to live with:
I mainly use scales to find the base coordinate. Then I add or withdraw a bit until I am satisfied with the location. This method does support field changes.

  //Create title svg.append("text") .attr("x", w / 2 ) .attr("y", yScale(d3.max(input, function(d) { return d.CustomerCount; })) - 20 ) .style("text-anchor", "middle") .text("Title of Graph"); //Create X axis label svg.append("text") .attr("x", w / 2 ) .attr("y", yScale(0) + 40 ) .style("text-anchor", "middle") .text("State"); //Create Y axis label svg.append("text") .attr("transform", "rotate(-90)") .attr("y", xScale(0) - 80 ) .attr("x",0 - (h / 2)) .attr("dy", "1em") .style("text-anchor", "middle") .text("Revenue"); 
+4
source share
1 answer

I use a simple function to measure text, and then calculates the fields based on this.

 // create a dummy element, apply the appropriate classes, // and then measure the element function measure(text, classname) { if(!text || text.length === 0) return {height: 0, width: 0}; var container = d3.select('body').append('svg').attr('class', classname); container.append('text').attr({x: -1000, y: -1000}).text(text); var bbox = container.node().getBBox(); container.remove(); return {height: bbox.height, width: bbox.width}; } 

Now you can use

 var titleSize = measure('my title', 'chart title'), margin.top = titleSize.height + 20; // add whatever padding you want 

I updated your example at http://jsfiddle.net/uzddx/2/ . When you change the font size of the header, you can see how the top margin changes. You can do something similar for the left margin so that your label is not so far from the y axis.

+12
source

All Articles