2015-04-17 186 views
0

當前正試圖在我的圖表上包裝一些文字標籤。我遵循Mike Bostock的例子here。當我嘗試實現他的例子時,它適用於我的y軸,但我需要它在我的x軸上工作,我不確定它爲什麼不起作用。包裝文字標籤

chart2.append("g") 
     .attr("class", "y axis") 
     .call(yAxis) 
     .append("text") 
     .attr("transform", "rotate(-90)") 
     .attr("y", 6) 
     .attr("dy", ".71em") 
     .style("text-anchor", "end") 
     .text("Potential Years Lost") 
     .call(wrap, x0.rangeBand()); 


    function wrap(text, width) { 
    text.each(function() { 
    var text = d3.select(this), 
     words = text.text().split(/\s+/).reverse(), 
     word, 
     line = [], 
     lineNumber = 0, 
     lineHeight = 1.1, // ems 
     y = text.attr("y"), 
     dy = parseFloat(text.attr("dy")), 
     tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em"); 
    while (word = words.pop()) { 
     line.push(word); 
     tspan.text(line.join(" ")); 
     if (tspan.node().getComputedTextLength() > width) { 
     line.pop(); 
     tspan.text(line.join(" ")); 
     line = [word]; 
     tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word); 
     } 
    } 
    }); 
} 

function type(d) { 
    d.value = +d.value; 
    return d; 
} 

這裏是我的小提琴:http://jsfiddle.net/flyingburrito/0xq0qc42/1/

回答

3

小的變化,你沒有實際調用在x軸的刻度文本wrap(你只稱這是爲y軸的標籤)。

您需要的最後兩行添加到該塊,其中X軸是附加

//draw the bars 
chart2.append("g") 
    .attr("class", "x axis") 
    .attr("transform", "translate(0," + height + ")") 
    .call(xAxis) 
    .selectAll(".tick text") 
    .call(wrap, x0.rangeBand()); 

工作小提琴這裏:http://jsfiddle.net/henbox/v5fj0263/

+0

唉唉吧!謝謝! – jmswng

0

或者你可以使用外部對象與HTML:

  1. 添加異物然後使用xhtml內容。

var fo = nodes.append("foreignObject") 
 
    .style("pointer-events", "none") 
 
    .attr("id", "fo") 
 
    .attr("width", function(d) { 
 
    return Math.max(32, this.getComputedTextLength() + 12); 
 
    }); 
 

 
fo.append("xhtml:body") 
 
    .style("text-align", "center") 
 
    .append("div") 
 
    .attr("class", "fotext") 
 
    .style("margin", "0px auto") 
 
    .style("font", "14px 'Helvetica Neue'") 
 
    .style("overflow", "auto") 
 
    .html(function(d) { 
 
    return d.name 
 
    }); 
 

 
fo.attr("transform", function(d) { 
 
    return translateInMiddle(this) 
 
}); 
 

 
function translateInMiddle(object) { 
 
    bbox = object.getBBox(); 
 
    return "translate(" + [-bbox.width/2, -bbox.height/8] + ")"; 
 
}