鉴于此数据:
[
{
date: new Date("2013-11-04T13:38:04.604Z"),
value: 3
}, {
date: new Date("2013-11-05T13:38:04.605Z"),
value: 50
}, {
date: new Date("2013-11-06T13:38:04.605Z"),
value: 71
}, {
date: new Date("2013-11-07T13:38:04.605Z"),
value: 84
}, {
date: new Date("2013-11-08T13:38:04.605Z"),
value: 85
}, {
date: new Date("2013-11-09T13:38:04.605Z"),
value: 16
}, {
date: new Date("2013-11-10T13:38:04.606Z"),
value: 38
}
];
我有一个应用程序,我想在其中为一周的数据绘制图表;周一开始,周日结束。我有 D3 来绘制图表,但问题是星期一点在 Y 轴上开始死了,并且所有 X 轴标签都没有正确对齐。我只是想知道是否可以使用一个函数来强制 D3 绘制特定的开始和结束日期,如果没有,至少将线上的数据点与 X 轴上的数据点对齐。我的代码如下所示:
// set up a drawing context
var margin = {
top: 40,
right: 40,
bottom: 70,
left: 100
};
var width = 940 - margin.left - margin.right;
var height = 530 - margin.top - margin.bottom;
// d3 init
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x).orient("bottom").ticks(7).tickFormat(d3.time.format('%a'));
var yAxis = d3.svg.axis().scale(y).orient("left").ticks(10);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"
);
var valueline = d3.svg.line()
.x(function(d) {
return x(d.date);
}).y(function(d) {
return y(d.value);
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain([0, d3.max(data, function(d) {
return d.value;
})]);
svg.append("path") // Add the valueline path.
.attr("d", valueline(data));
// Add the black dots
svg.selectAll("dot")
.data(data)
.enter().append("circle")
.attr("r", 5)
.attr("cx", function(d) { return x(d.date); })
.attr("cy", function(d) { return y(d.value); })
// Add the axes
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")").call(xAxis);
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
我在这里有一个“工作”的小提琴。任何建议将不胜感激; 我刚刚开始掌握 D3,这个问题让我有点困惑。