我正试图掌握D3,并希望沿着x轴绘制一个简单折线图7天的演示。到目前为止,我有http://jsfiddle.net/wRDXt/1/
// Define the resolution
var width = 500;
var height = 250;
// Create the SVG 'canvas'
var svg = d3.select("body")
.append("svg")
.attr("viewBox", "0 0 " + width + " " + height)
// get the data
var dataset = [
{ date: new Date(2013, 17, 1), value: 1 },
{ date: new Date(2013, 17, 2), value: 2 },
{ date: new Date(2013, 17, 3), value: 3 },
{ date: new Date(2013, 17, 4), value: 4 },
{ date: new Date(2013, 17, 5), value: 5 },
{ date: new Date(2013, 17, 6), value: 6 },
{ date: new Date(2013, 17, 7), value: 7 }
];
// Define the padding around the graph
var padding = 50;
// Set the scales
var minDate = d3.min(dataset, function(d) { return d.date; });
minDate.setDate(minDate.getDate() - 1);
var maxDate = d3.max(dataset, function(d) { return d.date; });
var xScale = d3.scale.linear()
.domain([minDate, maxDate])
.range([padding, width - padding]);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d.value; })])
.range([height - padding, padding]);
// x-axis
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.tickFormat("todo")
.tickSize(5, 5, 0)
svg.append("g")
.attr("class", "axis x-axis")
.attr("transform", "translate(0," + (height - padding) + ")")
.call(xAxis);
// y-axis
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.tickFormat(function (d) { return d; })
.tickSize(5, 5, 0)
.ticks(5); // set rough # of ticks
svg.append("g")
.attr("class", "axis y-axis")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
// Scatter plot
svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("class", "data-point")
.attr("cx", function(d) {
return xScale(d.date);
})
.attr("cy", function(d) {
return yScale(d.value);
})
.attr("r", 5);
// line graph
var line = d3.svg.line()
.x(function(d) {
return xScale(d.date);
})
.y(function(d) {
return yScale(d.value);
});
svg.append("svg:path").attr("d", line(dataset));
我遇到了一些问题:
答案 0 :(得分:5)
我已经更新了你的jsfiddle来做你想做的事情here。简单地说,我做了以下事情:
d3.time.days, 1
指定为ticks
。.tickFormat
功能。