Set the y axis of d3 to fit the widest label?

I draw line charts with d3 and everything works fine. However, I should leave enough margin to the left of the chart area to fit what, in my opinion, might be the widest text label of the y axis. I would like to customize this space for each chart, depending on the widest label.

Initially, I thought that I could find the maximum value of y, create a hidden text object, find out how wide it is, and use this value for the left margin when creating the chart. A little disgusting, but it brings me meaning.

However, if the maximum y value is, say, β€œ1598.538”, the topmost label of the Y axis can be β€œ1500” ... i.e. much narrower.

So, I think I want to find the width of what will actually be the brightest label. But I can’t think how to do this without drawing a diagram and an axis, measuring this width and not drawing it again for real. What sounds disgusting! Is there an unpleasant way to do this?

UPDATE

Here is part of my code using Lars' suggestion to show where it fits:

// I did have // `.attr("transform", "translate(" + margin.left + "," + margin.top ")")` // on the end of this line, but I've now moved that to the bottom. var g = svg.select("g"); // Add line paths. g.selectAll(".line").data(data) .enter() .append("path") .attr("d", line); // Update the previously-created axes. g.select(".axis-x") .attr("transform", "translate(0," + yScale.range()[0] + ")")) .call(xAxis); g.select(".axis-y") .call(yAxis); // Lars suggestion for finding the maximum width of a y-axis label: var maxw = 0; d3.select(this).select('.axis-y').selectAll('text').each(function(){ if (this.getBBox().width > maxw) maxw = this.getBBox().width; }); // Now update inner dimensions of the chart. g.attr("transform", "translate(" + (maxw + margin.left) + "," + margin.top + ")"); 
+7
source share
1 answer

You can put everything in the g element and set the transform based on the maximum width. Something along the lines

 var maxw = 0; yAxisContainer.selectAll("text").each(function() { if(this.getBBox().width > maxw) maxw = this.getBBox().width; }); graphContainer.attr("transform", "translate(" + maxw + ",0)"); 
+6
source

All Articles