使用d3.js我想表示区域图表。 我从JSON数组中获取数据,如下所示:
[{"time":"00:00 - 00:15","energy":10},
{"time":"00:15 - 00:30","energy":20},
{"time":"00:30 - 00:45","energy":30},
{"time":"00:45 - 01:00","energy":50},
{"time":"01:00 - 01:15","energy":60},
{"time":"01:15 - 01:30","energy":70}...]
为了在x轴(时间)中表示域,我已经硬编码了域的所有96个元素,如下所示:
x.domain(["00:00 - 00:15","00:15 - 00:30","00:30 - 00:45","00:45 - 01:00",
"01:00 - 01:15","01:15 - 01:30","01:30 - 01:45","01:45 - 02:00",
"02:00 - 02:15","02:15 - 02:30","02:30 - 02:45","02:45 - 03:00",
"03:00 - 03:15","03:15 - 03:30","03:30 - 03:45","03:45 - 04:00",
"04:00 - 04:15","04:15 - 04:30","04:30 - 04:45","04:45 - 05:00",
"05:00 - 05:15","05:15 - 05:30","05:30 - 05:45","05:45 - 06:00",
"06:00 - 06:15","06:15 - 06:30","06:30 - 06:45","06:45 - 07:00",
"07:00 - 07:15","07:15 - 07:30","07:30 - 07:45","07:45 - 08:00",
"08:00 - 08:15","08:15 - 08:30","08:30 - 08:45","08:45 - 09:00",
"09:00 - 09:15","09:15 - 09:30","09:30 - 09:45","09:45 - 10:00",
"10:00 - 10:15","10:15 - 10:30","10:30 - 10:45","10:45 - 11:00",
"11:00 - 11:15","11:15 - 11:30","11:30 - 11:45","11:45 - 12:00",
"12:00 - 12:15","12:15 - 12:30","12:30 - 12:45","12:45 - 13:00",
"13:00 - 13:15","13:15 - 13:30","13:30 - 13:45","13:45 - 14:00",
"14:00 - 14:15","14:15 - 14:30","14:30 - 14:45","14:45 - 15:00",
"15:00 - 15:15","15:15 - 15:30","15:30 - 15:45","15:45 - 16:00",
"16:00 - 16:15","16:15 - 16:30","16:30 - 16:45","16:45 - 17:00",
"17:00 - 17:15","17:15 - 17:30","17:30 - 17:45","17:45 - 18:00",
"18:00 - 18:15","18:15 - 18:30","18:30 - 18:45","18:45 - 19:00",
"19:00 - 19:15","19:15 - 19:30","19:30 - 19:45","19:45 - 20:00",
"20:00 - 20:15","20:15 - 20:30","20:30 - 20:45","20:45 - 21:00",
"21:00 - 21:15","21:15 - 21:30","21:30 - 21:45","21:45 - 22:00",
"22:00 - 22:15","22:15 - 22:30","22:30 - 22:45","22:45 - 23:00",
"23:00 - 23:15","23:15 - 23:30","23:30 - 23:45","23:45 - 00:00"]);
这很有效,
但我想转向更优雅的东西,比如使用d3.min()和d3.max()。但这不起作用。这是我的代码。
x.domain([d3.min(json, function(d){return d["time"]}),d3.max(json, function(d){return d["time"]})]);
和图形结果。
我有两个问题:
1-这是在一行中定义我的域名的任何方式吗?我已经检查了时间刻度,但我不知道如何将它集成到我的代码中,如果可以在四分之一区间内使用它。如果我使用scale.ticks(d3.time.minutes, 15)
,我不知道如何匹配域和我的JSON数据定义。
2-如果您看到我的第一个图表的底部,则勾选文本已被覆盖。我想代表几个小时(每4个季度1个小时)。我怎么能这样做?
提前致谢。
答案 0 :(得分:4)
要按照您当前的方式定义域,请使用此代码。
x.domain(json.map(function(d) {return d["time"];} ));
格式化时间轴(实际上min
和max
)的常用函数不起作用的原因是,就Javascript而言,您的日期只是字符串。您需要将它们解析为日期才能使用特定时间轴的东西。为此,您需要决定是否采用间隔的起点或终点。
The documentation在解析和格式化日期和时间方面有更多。
答案 1 :(得分:0)
如果要重现已经硬编码的内容,则需要由字符串表示的类别形成的离散域,而不是连续域。
因此,您需要为您的域生成字符串数组
sprintf = require("sprintf").sprintf;
var categories = new Array;
for (var i=0, t1=0, t2=15; i<24*4; i++, t1+=15, t2+=15) {
categories[i]=sprintf(
"%02d:%02d - %02d:%02d",
Math.floor(t1/60),t1%60,Math.floor(t2/60),t2%60
);
}
并传递该数组
x.domain(categories)
另一种选择是改变&#34;时间&#34;原始json数据的值为实时值,而不是字符串。但这是另一个SO帖子。