【发布时间】:2014-03-28 20:49:55
【问题描述】:
我通常使用以下方法将轴刻度放在 svg 上:
d3.svg.axis().scale(xScale(width)).ticks(4)
是否可以获得这些刻度值及其 svg 坐标,以便我可以使用 d3.svg.axis() 在 svg 之外使用自定义轴?
【问题讨论】:
-
如果你打电话给
xScale.ticks(),你应该得到它们。
标签: d3.js
我通常使用以下方法将轴刻度放在 svg 上:
d3.svg.axis().scale(xScale(width)).ticks(4)
是否可以获得这些刻度值及其 svg 坐标,以便我可以使用 d3.svg.axis() 在 svg 之外使用自定义轴?
【问题讨论】:
xScale.ticks(),你应该得到它们。
标签: d3.js
是的,xScale.ticks(4) 应该为您提供实际的滴答点作为值,您可以通过您的xScale 将它们返回到 X 位置。在将轴应用于实际元素后,您也可以将刻度点从生成的元素中拉回:
var svg = d3.select("svg");
var scale = d3.scale.linear()
.range([20, 280])
.domain([0, 100])
var axis = d3.svg.axis().scale(scale).orient("bottom").ticks(9);
// grab the "scale" used by the axis, call .ticks()
// passing the value we have for .ticks()
console.log("all the points", axis.scale().ticks(axis.ticks()[0]));
// note, we actually select 11 points not 9, "closest guess"
// paint the axis and then find its ticks
svg.call(axis).selectAll(".tick").each(function(data) {
var tick = d3.select(this);
// pull the transform data out of the tick
var transform = d3.transform(tick.attr("transform")).translate;
// passed in "data" is the value of the tick, transform[0] holds the X value
console.log("each tick", data, transform);
});
【讨论】:
axis.scale().ticks(),或者只是someScaleObject.ticks() if the scale obj is accessible)
在 d3 v4 中,我最终只是从刻度节点解析渲染的 x 值
function parseX(transformText) {
let m = transformText.match(/translate\(([0-9\.]*)/);
let x = m[1];
if (x) {
return parseFloat(x);
}
}
【讨论】: