簡體   English   中英

將d3圖表的y軸設置為適合最寬的標簽?

[英]Set y-axis of d3 chart to fit widest label?

我正在用d3繪制折線圖,​​並且一切正常。 但是,我必須在圖表區域的左側保留足夠的邊距,以適合我認為可能是最寬的y軸文本標簽的內容。 我想為每個圖表調整此空間,具體取決於最寬的標簽。

最初,我以為我可以找到y的最大值,創建一個隱藏的文本對象,計算出它的寬度,並在創建圖表時使用該值作為左邊距。 有點討厭,但它給我帶來了價值。

但是,如果最大y值是“ 1598.538”,則最頂部的y軸標簽可能是“ 1500” ...,即,窄得多。

所以我想我想找到實際上將是最上面的標簽的寬度。 但我想不出繪制圖表和軸,測量該寬度並再次將其重新繪制成實線的方法。 聽起來很討厭! 有沒有討厭的方式來做到這一點?

更新

這是我的代碼的一部分,使用Lars的建議,只是為了表明它適合的位置:

// 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's 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 + ")");

您可以將所有內容放入g元素內,並根據最大寬度設置transform 遵循以下原則

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM