gpt4 book ai didi

javascript - 在 d3.js 中如何将数字标签移离 x 轴更远?

转载 作者:行者123 更新时间:2023-12-01 14:15:20 25 4
gpt4 key购买 nike

新手问题:如何将 x 轴刻度标签从 x 轴移得更远?下面的代码片段产生了这个:

current

而我想要的更像这样:

desired

来自这里的问题:

d3.js: Align text labels between ticks on the axis

看来我需要使用 select 选择包含这些标签的文本,然后对它们应用 translate(0,-10) 之类的东西,但我可以弄清楚此文本“存在”的位置/执行此类选择的语法。对不起,如果这很简单;我对 D3(和 javascript)很陌生。谁能帮忙?提前致谢!代码如下。

<script>

var superscript = "⁰¹²³⁴⁵⁶⁷⁸⁹",
formatPower = function(d) { return (d + "").split("").map(function(c) { return superscript[c]; }).join("");\
};

var margin = {top: 20, right: 20, bottom: 100, left: 100},
width = 400,
height = 400;

var x = d3.scale.log()
.domain([1e1, 1e4])
.range([0, width])
.nice();

var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickValues([1e1, 1e2, 1e3, 1e4])
.ticks(0, function(d) { return 10 + formatPower(Math.round(Math.log(d) / Math.LN10)); });

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

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("class", "label")
.attr("x", (width+margin.left)/2)
.attr("y", 60)
.style("text-anchor", "end")
.text("x-axis label");

</script>

最佳答案

有一种更简单的方法可以使用 tickPadding 来做到这一点.在定义 xAxis 的地方,只需添加 .tickPadding(15)(将 15 更改为您想要的像素数)。

此处示例:http://jsfiddle.net/henbox/5q4k2r0p/1/

关于javascript - 在 d3.js 中如何将数字标签移离 x 轴更远?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26700510/

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