简体   繁体   English

缩放d3时间轴的更好方法

[英]Better way to scale d3 time axis

I'm trying to draw a line using D3.js. 我正在尝试使用D3.js画一条线。 They are samples taken at intervals over a period of time. 它们是在一段时间内间隔采样的样本。 I want to draw them with a time axis for x. 我想用x的时间轴来绘制它们。 Each point of data is just an index in an array and I can't figure out how to set up my axis in such a way that I don't have to manually re-scale the axis before calling d3.time.scale. 数据的每个点都只是数组中的索引,我无法弄清楚如何设置轴,而不必在调用d3.time.scale之前手动重新缩放轴。

Does anyone know how to clean up the scale? 有人知道如何清理秤吗?

Snippets out of my code. 我的代码片段。 My actual code downloads the data and draws a lot of lines over different time periods with different offsets translated in the graph. 我的实际代码下载了数据,并在不同的时间段绘制了许多线,并在图形中转换了不同的偏移量。

// input data
var start_time = 1352684763;
var end_time = 1352771163;
// data is exactly 100 samples taken between start_time and end_time
var data = [140,141,140,140,139,140,140,140,140,141,139,140,54,0,0,0,0,0,0,0,0,0...]
var y_max = d3.max(data);

// graph
var scale_x = d3.time.scale().domain([start_time, end_time]).range([0, 100]);
var scale_y = d3.scale.linear().domain([0, y_max]).range([height, 0]);
var step = (end_time - start_time)/100;
function re_scale(x) { return start_time + x*step; }

// for x, rescale i (0..99) into a timestamp between start_time and end_time before returning it and letting scale_x scale it to a local position. Awkward.
var line = d3.svg.line()
    .x(function(d, i) { return scale_x(re_scale(i)); })
    .y(scale_y)
    .interpolate('basis')

var g = graph.selectAll("g")
    .append('svg:path')
    .attr('d', function(d) { return line(data); })

// also draw axis here...

The "domain" should refer to the span in the data, and the "range" should refer to the span on the screen. “域”应指数据中的跨度,“范围”应指屏幕上的跨度。

At the moment it would be interpreting .range([0, 100]) on scale_x as a number of pixels. 目前,它将.range([0, 100])解释为许多像素。 If you change this to .range([0, width]) it should work without needing to re-scale. 如果将其更改为.range([0, width])它应该工作而无需重新缩放。

d3.time.scale() only needs to know the start and end points to produce a good axis. d3.time.scale()只需要知道起点和终点即可产生一个良好的轴。 However if you do want a tick for every data point there are options do do this in the docs . 但是,如果您确实希望为每个数据点都打勾,则可以在docs中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM