【问题标题】:d3.js how to place custom labels on horizontal log scaled axisd3.js 如何在水平对数缩放轴上放置自定义标签
【发布时间】:2012-05-23 12:08:48
【问题描述】:

我正在使用 d3.js 绘制图表,使用 d3.scale.log 作为 x 轴并结合自定义标签。不幸的是,标签相互碰撞......关于如何使这项工作的任何提示?

var width = 400;
var x = d3.scale.log().domain([1, 1000]).range([0, width]);

var formatSi = d3.format(".4s");
var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .tickFormat(function(d, i) {
        return formatSi(d) + 'Hz'
    });

var svg = d3.select("#chart")
    .append("svg").attr("width", width)
    .attr("height", 200)
    .append("g").attr("transform", "translate(20,20)");

([1, 3, 6, 9]).forEach(function(d) {
    x.domain([1, Math.pow(10, d)]);
    svg.append("g").attr("class", "axis x")
        .attr("transform", "translate(0," + d * 2 + "0)")
        .call(xAxis);
});​

此代码的工作示例位于 jsfiddle

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    想通了。诀窍是使用.tickFormat 来提供格式化函数,而是使用.ticks 方法,然后将提供的格式化函数应用于比例尺的.tickFormat 方法。

    var width = 400;
    var x = d3.scale.log().domain([1, 1000]).range([0, width]);
    
    var formatSi = d3.format(".4s");
    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
    ​    .ticks(5,function(d, i) {
            return formatSi(d) + 'Hz';
        });
    
    var svg = d3.select("#chart")
        .append("svg").attr("width", width)
        .attr("height", 200)
        .append("g").attr("transform", "translate(20,20)");
    
    ([1, 3, 6, 9]).forEach(function(d) {
        x.domain([1, Math.pow(10, d)]);
        svg.append("g").attr("class", "axis x")
            .attr("transform", "translate(0," + d * 2 + "0)")
            .call(xAxis);
    });
    

    结果仍然不完全令人满意,因为当刻度靠近时系统似乎无法放置标签...

    【讨论】:

    • 这对我不起作用,我在 x 轴上有一个带有用户名的条形图,我不能跳过会跳过用户名但显示该名称数据的“刻度”。除此之外,它也不起作用。 d3.v3
    • 这对我也不起作用,我收到了Object function .. has no method 'replace'
    猜你喜欢
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多