我正在进行视觉化http://bost.ocks.org/mike/nations/:
我对插值函数有疑问。最初调用mousemove调用displayYear,调用interpolate数据。
function mousemove() {
displayYear(yearScale.invert(d3.mouse(this)[0]));
}
}
// Tweens the entire chart by first tweening the year, and then the data.
// For the interpolated data, the dots and label are redrawn.
function tweenYear() {
var year = d3.interpolateNumber(thisyear, 2009);
return function(t) { displayYear(year(t)); };
}
// Updates the display to show the specified year.
function displayYear(year) {
//alert(year);
thisyear=year;
dot.data(interpolateData(year), key).call(position).sort(order);
label.text(Math.round(year));
}
// Interpolates the dataset for the given (fractional) year.
function interpolateData(year) {
return nations.map(function(d) {
return {
name: d.name,
region: d.region,
checkins: interpolateValues(d.checkins, year),
teamsize: interpolateValues(d.teamsize, year),
Checkintimes: interpolateValues(d.Checkintimes, year)
};
// Finds (and possibly interpolates) the value for the specified year.
function interpolateValues(values, year) {
var i = bisect.left(values, year, 0, values.length - 1),
a = values[i];
if (i > 0) {
var b = values[i - 1],
t = (year - a[0]) / (b[0] - a[0]);
return a[1] * (1 - t) + b[1] * t;
}
return a[1];
}
这个功能有什么作用?我尝试调试,发现它比较2年并进行计算,然后返回值。任何人都可以详细说明这个吗?
json文件包含
[
{
"name":"India",
"region":"South Asia",
"income":[[2000,225],[2001,225],[2002,226],[2003,227],[2004,229],[2005,230],[2006,231],[2007,244],[2008,254],[2009,253]],
"population":[[2000,41542812],[2001,41623424],[2002,41866106],[2003,42186202],[2004,41521432],[2005,41827315],[2006,42127071],[2007,42420476],[2008,42707546],[2009,42707546]],
"lifeExpectancy":[[2000,43.56],[2001,43.86],[2002,44.22],[2003,64.61],[2004,56.05],[2005,56.52],[2006,66.02],[2007,68.54],[2008,67.06],[2009,73.58]]
}
]
答案 0 :(得分:1)
此代码的用途是缺少一年(或更多)数据的情况,在您发布的示例数据中似乎不是这种情况。首先,它使用bisect.left
找到与给定年份最接近的数据点,然后计算先前数据点与请求年份的当前数据点之间的推断。
请特别注意,您的案例中的year - a[0]
将始终为0,因为所有年份都存在(这会计算请求和找到的年份之间的差异)。因此,整个项将为0,返回值对应a[1]
。
如果请求的年份不存在,t
表示描述上一年b
与当前年a
之间变化的因素。此更改因子用于推断过去a
以获取所请求年份的值。