javascript - 设置 d3 图表的 y 轴以适合最宽的标签?

标签 javascript d3.js label linechart

我正在使用 d3 绘制折线图,​​一切正常。但是,我必须在图表区域的左侧留出足够的边距以适应我认为最宽的 y 轴文本标签。我想根据最宽的标签为每个图表调整此空间。

最初我以为我可以找到最大的 y 值,创建一个隐藏的文本对象,计算出它的宽度,并在创建图表时使用该值作为左边距。有点讨厌,但它给我带来了值(value)。

但是,如果最大 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)");

关于javascript - 设置 d3 图表的 y 轴以适合最宽的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17109549/

相关文章:

javascript - D3.js 图表画笔和 Crossfilter.js 缩放不同步

swift - 在编程 collectionviewCell 中添加约束

ios - 如何修复 : Type 'String' does not conform to protocol 'SequenceType' in Swift

javascript - 如何在Vuejs中过滤对象的属性

javascript - 如何使用新的 props 更新模态组件

javascript - D3 circle pack - 向节点添加标签

javascript - 在 c3 中有条件地添加或省略 JavaScript 属性

javascript - 对于非单页应用程序,我应该在每个页面中使用 ng-app 指令吗?

javascript - React - Google Map 组件在重新渲染后不会更改 map

xamarin - 将 markdown 文本加载到 Xamarin.Forms 标签中