在已知索引范围内的日期之间进行插值 [英] interpolate between dates given known index range
问题描述
我正在尝试填充一些硬编码的数据". x轴是时间(以年为单位),y轴是数值.该图将类似于指数函数.这是我到目前为止的内容,您会注意到索引范围(表示为n)为100:
I am trying to populate some hard coded "data." The x axis is time in years, and the y axis is a numerical value. The graph will resemble an exponential function. Here is what I have so far, you'll notice the index range (denoted as n) is 100:
var data = [];
var n = 100;
var a = 1;
var b = 2;
for(var k = 0; k <100; k++) {
data.push({x: ???, y: a * Math.pow(b, 0.01 * k)});
}
我不太清楚如何在日期之间进行插值.我的第一个尝试是从最初的年份开始,然后增加增量,然后强制转换为String()
一年,但是最后我发现不再是日期.数学运算不知道我想要日期输出,所以我想那是我的错.而且我还没有想出更好的方法.
I couldn't quite figure out how to interpolate between dates. My first try was starting with my initial year and adding increments then casting into String()
for a year, but I wound up with something that was no longer a date. Math operations didn't know I wanted a date output, so I suppose that's my fault. And I have yet to think of a better way.
问题:
如何在for循环中的javascript中的两个日期之间插值?
How do I interpolate between two dates in javascript within a for loop?
- 开始日期:1800-01-01
- 结束日期:2020年1月1日
- n:100
推荐答案
通过使用时间标尺和invert
方法,您可以获得真实日期对象,而不仅仅是伪装成日期的字符串.
You can get real date objects, not just strings disguised as dates, by using a time scale and the invert
method.
为此,我们只需要设置变量...
For that to work, we just need to set the variables...
var n = 100;
var a = 1;
var b = 2;
var startDate = "1800-01-01";
var endDate = "2020-01-01";
...和解析器:
var parser = d3.timeParse("%Y-%m-%d");
现在我们设置比例.重要的是将其设置为从0
到100
的范围.这是我们将与invert
一起使用的范围,以获取对应的日期:
Now we set the scale. The important part is setting it's range from 0
to 100
. It's the range that we'll use with invert
, to get the correspondent date:
var scale = d3.scaleTime()
.domain([parser(startDate), parser(endDate)])
.range([0, n]);
最后,我们创建数组.我们可以使用d3.range
并摆脱for循环:
Finally we create the array. We can use d3.range
and get rid of the for loop:
var data = d3.range(n).map(function(k) {
return {
x: scale.invert(k),
y: a * Math.pow(b, 0.01 * k)
}
});
这是演示:
var n = 100;
var a = 1;
var b = 2;
var startDate = "1800-01-01";
var endDate = "2020-01-01";
var parser = d3.utcParse("%Y-%m-%d");
var scale = d3.scaleTime()
.domain([parser(startDate), parser(endDate)])
.range([0, n]);
var data = d3.range(n).map(function(k) {
return {
x: scale.invert(k),
y: a * Math.pow(b, 0.01 * k)
}
})
console.log(data)
<script src="https://d3js.org/d3.v5.min.js"></script>
这篇关于在已知索引范围内的日期之间进行插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!