我正在d3中做一个项目,并且在我的智慧结束时如何为绘制推文绘制频率图。所以,基本上,我有一个JSON文件,其格式是这样的
{ "text": "some text here", "time": "timestamp here", "timezone": "timezone here", "retweet_count": some number, "hashtags": "some text here" }
所以,现在我需要在d3中绘制一个图表,显示特定时间段内的推文数量。例如,在日期X和日期Y之间,图表显示每天有多少推文。
有人可以帮我解决这个问题吗?我真的很喜欢d3。
答案 0 :(得分:3)
您应该可以使用d3 time scale和intervals一起为您进行分箱。类似的东西:
var data= [
{time: 'Jan. 1, 2012 13:00', name:"test", value:2},
{time: 'Jan. 2, 2012 9:00', name:"test", value:2},
{time: 'Jan. 3, 2012 14:00', name:"test", value:2},
{time: 'Jan. 1, 2012 12:30', name:"test", value:2},
{time: 'Jan. 3, 2012 1:00', name:"test", value:2},
{time: 'Jan. 3, 2012 1:10', name:"test", value:2},
{time: 'Jan. 3, 2012 1:20', name:"test", value:2},
{time: 'Jan. 3, 2012 2:00', name:"test", value:2},
{time: 'Jan. 1, 2012 3:00', name:"test", value:2},
];
// Get the date range from the data - could also be hardcoded
var dateRange = d3.extent(data, function(d) { return new Date(d.time); });
console.log("Data range", dateRange); // This will output your data's time range
// This will compute time bins
var binner = d3.time.scale();
// Pick the interval I want to bin on
var interval = d3.time.day; // Use hour, or minute, etc.
// I will compute the number of the time intervals I want
var allIntervals = interval.range(interval.floor(dateRange[0]), interval.ceil(dateRange[1]));
console.log("Intervals", allIntervals); // This will output an array of all the days/hours/whatever between min and max date
// Input domain mapped to output range
binner.domain([allIntervals[0], allIntervals[allIntervals.length - 1]]);
binner.range([0,allIntervals.length - 1]);
// Make sure we only output integers - important because we will fill an array
binner.interpolate(d3.interpolateRound);
// Empty histogram
var hist = [];
for(var i=0; i < allIntervals.length; i++) hist[i] = 0;
data.forEach(function(d) {
// Compute the hour index
var tid = binner(interval.floor(new Date(d.time)));
console.log("Map " + d.time + " to " + tid);
if(!hist[tid]) {
hist[tid] = 1;
}
else {
hist[tid]++;
}
});
// Here is the histogram.
console.log("Hist:",hist);
我把它与一个非常基本的直方图here
放在一起请注意,您可以用一些毫秒数学代替interval.range(...)调用,以提高性能,但是如果您想要执行工具提示,那么将所有值都有用。