简体   繁体   English

如何在d3.js中修改处理日期的域?

[英]How to modify a domain dealing with dates in d3.js?

I am studying this example: https://bl.ocks.org/d3noob/2505b09d0feb51d0c9873cc486f10f67 made by d3noob and I realized that the first and the last dot are partially in the margins. 我正在研究这个例子: https://bl.ocks.org/d3noob/2505b09d0feb51d0c9873cc486f10f67通过d3noob量身定做的,我意识到,第一和最后一个点是部分的利润。 I am wondering how to make a buffer on each side of the x.domain in order to keep the dots away from the margins. 我想知道如何在x.domain的每一侧上做一个缓冲区,以使点距边距不远。

I believe that the line responsible of this is the following: 我相信对此负责的热线如下:

x.domain(d3.extent(data, function(d) { return d.date; }));

I tried to modify this line with d3.min and d3.max but this doesn't seem to work as the x axis is dealing with dates. 我试图用d3.min和d3.max修改此行,但这似乎不起作用,因为x轴正在处理日期。

You can add or subtract time (in this case, days) using interval.offSet . 您可以使用interval.offSet增减时间(在本例中为天)。

For instance, subtracting 2 days from the start and adding 2 days in the end of the x domain: 例如,从x域的开始减去2天,在x域的末尾增加2天:

x.domain([d3.timeDay.offset(d3.min(data, function(d) {
    return d.date;
}), -2), d3.timeDay.offset(d3.max(data, function(d) {
    return d.date;
}), +2)]); 

Here is the updated bl.ocks: https://bl.ocks.org/anonymous/f4bb84ba833b6f8ec9ddd3e8281abc44/79839a6a937d712edca8a7c8f00e4301723726c3 这是更新的bl.ocks: https ://bl.ocks.org/anonymous/f4bb84ba833b6f8ec9ddd3e8281abc44/79839a6a937d712edca8a7c8f00e4301723726c3

You might want to consider trying the d3fc extent component . 您可能需要考虑尝试d3fc范围组件 In your case, you can add one day on either side of the x scale as follows: 在您的情况下,您可以在x比例尺的任一侧添加一天,如下所示:

var xExtent = fc.extentDate()
   // the property of the data that defines the x extent
  .accessors([function(d) { return d.date; }])
  // pad in domain units (in this case milliseconds)
  .padUnit('domain')
  // ensure that the scale is padded by one day in either direction
  .pad([millisPerDay, millisPerDay]);

x.domain(xExtent(data));

You can also use this component to simplify the computation of the y domain extent: 您还可以使用此组件来简化y域范围的计算:

var yExtent = fc.extentLinear()
  // the property of the data that defines the y extent
  .accessors([function(d) { return d.close; }])
  // pad by 10% in the +ve direction
  .pad([0, 0.1])
  // ensure that the extent includes zero
  .include([0]);

y.domain(yExtent(data));

Here's a complete example: https://bl.ocks.org/ColinEberhardt/4b8737e0251f92075693a6e04df72638 这是一个完整的示例: https : //bl.ocks.org/ColinEberhardt/4b8737e0251f92075693a6e04df72638

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

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