标题和轴标签

Dat*_*vid 4 label axis title d3.js

我成功地为X轴和Y轴创建了标签.我也成功地为图表添加了标题.我的问题是,如果我修改图形的边距,标签位置会搞砸.

我更改图表边距的片段:

    var margin = {top: 60, right: 60, bottom: 60, left:120}  
Run Code Online (Sandbox Code Playgroud)

我创建标签的片段:

    //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");  
Run Code Online (Sandbox Code Playgroud)

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

这是我愿意接受的另一种选择:
我基本上利用比例来找到基本坐标.然后我添加或采取一点点直到我对位置感到满意.这种方法实际上跟上了边距的变化.

    //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"); 
Run Code Online (Sandbox Code Playgroud)

Bil*_*ill 12

我使用一个简单的函数来测量文本,然后根据它计算边距.

// 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};
}
Run Code Online (Sandbox Code Playgroud)

现在你可以使用了

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

我在http://jsfiddle.net/uzddx/2/上更新了你的例子.修改标题的字体大小时,可以看到上边距调整大小.你可以为左边距做类似的事情,这样你的标签就不会离y轴太远了.