d3 convert x axis from array indices to dates

ぃ、小莉子 提交于 2020-01-05 08:46:18

问题


I have a data that is an array of values, like this:

[244, 13, 24, 0, 18, 24, 3, 4, ... ]

While array indices are simply integers, in this data they represent a range of dates such that the 0th index represents, say, 06/04/2013 and the last index represents 09/30/2013 although they're actually in seconds since 1970, so 1370378409 and 1380575923 would be more precise.

I would like my x-axis to show the dates that the array indices represent. So that the ticks would look like dates: Mon 08, Tue 09 and so on. As the data will change, I cannot know what the ticks should be ahead of time.. I'm hoping they can be calculated from the endpoints which I do know.

Theoretically, I'm thinking that I can convert from the domain of the x-axis (the chart's width) to the date range represented in the array. Something like this (but this didn't work in this formulation):

var xAsTime = d3.time.scale()
                 .domain([0, width])
                 .range([startDate, endDate])

which should nicely translate from integers to dates.


回答1:


The x function usually scales from your data domain to the range needed which is often the width of your chart. This is how you'll find things in many examples.

Usually to create axes, you pass to d3.svg.axis() your x function. However, the main job of the x function is often to create, in my case, the bars of a bar chart.

My own x function that I'm using in this bar chart:

var x = d3.scale.linear()
            .domain([0, data.length])
            .rangeRound([0, width]);

Here's one from MBostock:

var x = d3.scale.ordinal()
            .rangeRoundBands([0, width], .1);

And another with a JSFiddle:

var x = d3.time.scale()
            .domain([new Date(data[0].date),
                    d3.time.day.offset(new Date(data[data.length - 1].date), 1)])
            .rangeRound([0, width - margin.left - margin.right]);

Using the power and simplicity of d3 scales, I was able to solve this problem by converting from array indices to dates with a separate x function, xAsTime, like so:

var xAsTime = d3.time.scale()
                  .domain([this.start * 1000, this.end * 1000])
                  .range([0, width])

var xAxis = d3.svg.axis()
                .scale(xAsTime)
                .tickSize(-height)
                .tickPadding(3);

As per my question, the only change was to switch the domain and ranges. While I unsure of the details, it seems like the domain of the scale is what is displayed as ticks.




回答2:


d3 has a built in time scale specifically for this purpose:

https://github.com/mbostock/d3/wiki/Time-Scales



来源:https://stackoverflow.com/questions/20206020/d3-convert-x-axis-from-array-indices-to-dates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!