gpt4 book ai didi

javascript - 如何在 D3 折线图上安装可变长度刻度标签?

转载 作者:可可西里 更新时间:2023-11-01 02:05:11 27 4
gpt4 key购买 nike

这是一个 JSFiddle:http://jsfiddle.net/8p2yc/ (此处稍作修改的示例:http://bl.ocks.org/mbostock/3883245)

正如您在 JSFiddle 中看到的,沿 y 轴的刻度标签不适合 svg。我知道我可以增加左边距,但问题是我事先不知道数据是什么。如果我只是将页边距设置得非常大,如果数字的长度很短,图表就会显得很尴尬。

有没有办法在创建图表时预先计算最大标签宽度以正确设置边距?或者也许有一个完全不同的解决方案?

var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 400 - margin.left - margin.right,
height = 200 - margin.top - margin.bottom;

var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

example chart

谢谢!

最佳答案

您可以通过为最大标签附加文本、对其进行测量并在之后立即将其删除来实现此目的:

var maxLabel = d3.max(data, function(d) { return d.close; }),
maxWidth;
svg.append("text").text(maxLabel)
.each(function() { maxWidth = this.getBBox().width; })
.remove();

然后您可以使用该宽度来翻译 g 元素:

svg.attr("transform", "translate(" + Math.max(margin.left, maxWidth) + "," + margin.top + ")");

完整示例 here .

编辑:获得实际标签的最大长度有点复杂,因为您必须生成它们(使用正确的格式)并测量它们。这是一种更好的方法,因为您正在测量实际显示的内容。代码类似:

var maxWidth = 0;
svg.selectAll("text.foo").data(y.ticks())
.enter().append("text").text(function(d) { return y.tickFormat()(d); })
.each(function(d) {
maxWidth = Math.max(this.getBBox().width + yAxis.tickSize() + yAxis.tickPadding(), maxWidth);
})
.remove();

我将刻度线的大小以及刻度线和标签之间的填充添加到此处的宽度。完整的例子here .

关于javascript - 如何在 D3 折线图上安装可变长度刻度标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21603800/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com