【问题标题】:Use words as tick labels with unequal intervals in D3.js在 D3.js 中使用单词作为不等间隔的刻度标签
【发布时间】:2016-10-05 11:19:00
【问题描述】:

我正在创建一个包含多年数据的 D3.js 图。我想使用月份名称作为轴标签。我目前正在使用与该月的第一天对应的一年中的天数作为标签,如我的 x 轴屏幕截图所示:

我相信所有相关代码如下所示:

var margins = {'top' : 20, 'right' : 20, 'bottom' : 50, 'left' : 70};
var height = 500;
var width = 960;
var plotHeight = height - margins.top - margins.bottom;
var plotWidth = width - margins.right - margins.left;

var x = d3.scaleLinear()
    .domain([0,366])
    .range([margins.left, plotWidth]);

// I am not concerned with leap years
var monthDays = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
var monthAbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

var svg = d3.select('.svg').attr('width',width).attr('height',height);

svg.append('g').attr('transform', 'translate(0,' + plotHeight + ')').call(d3.axisBottom(x).tickValues(monthDays));

有没有办法将 x 轴上的位置映射到正确的月份(即:31 到 2 月)?我尝试过使用 d3.timeMonth/d3.timeMonths 和序数刻度,但还没有找到合适的东西。

【问题讨论】:

    标签: date d3.js axis-labels


    【解决方案1】:

    你可以使用tickFormat:

    .tickFormat(function(d,i){ return monthAbr[i]})
    

    这是一个基于您的代码的工作演示:

    var margins = {'top' : 20, 'right' : 20, 'bottom' : 50, 'left' : 20};
    var height = 100;
    var width = 600;
    var plotHeight = height - margins.top - margins.bottom;
    var plotWidth = width - margins.right - margins.left;
    
    var x = d3.scaleLinear()
        .domain([0,366])
        .range([margins.left, plotWidth]);
    
    // I am not concerned with leap years
    var monthDays = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
    var monthAbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    
    var svg = d3.select('body').append("svg").attr('width',width).attr('height',height);
    
    svg.append('g').attr('transform', 'translate(0,' + plotHeight + ')').call(d3.axisBottom(x).tickValues(monthDays).tickFormat(function(d,i){ return monthAbr[i]}));
    <script src="https://d3js.org/d3.v4.min.js"></script>

    【讨论】:

    • 这正是我想要的。我想会有一个简单的解决方法。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    • 2013-08-29
    • 2013-09-27
    • 1970-01-01
    相关资源
    最近更新 更多