d3.js时间轴上的垂直线

时间:2015-04-28 04:12:07

标签: javascript date d3.js

我正在尝试使用d3js库在时间轴上绘制垂直线。 x轴是2015年。我希望今天的垂直线代表(今天总是当天)。我遇到的问题是弄清楚如何将日期精确地作为坐标提供,以便正确绘制图形。 Here is the jsfiddle for the code.

var margin = {top: 10, right: 10, bottom: 30, left: 10},
width = 1200 - margin.left - margin.right,
height = 800 - margin.top - margin.bottom;

var x = d3.time.scale()
.domain([new Date(2015, 0, 1), new Date(2015, 11, 31)])
.range([0, width]);

var y = d3.scale.linear()
.domain([0,1000])
.range([height, 0]);

var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(d3.time.months)
.tickSize(30, 0)
.tickFormat(d3.time.format("%B"));

var xAxisMinor = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(d3.time.months)
.tickSize(-height)
.tickFormat(d3.time.format("%B"));

var xAxisMinorTicks = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(d3.time.weeks)
.tickSize(-height)
.tickFormat(d3.time.format("%U"));

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 + ")");


svg.append("rect")
.attr("class", "grid-background-light")
.attr("width", width)
.attr("height", height + margin.bottom)
.attr("rx", 5)
.attr("ry", 5);

svg.append("rect")
.attr("class", "grid-background")
.attr("width", width)
.attr("height", 30)
.attr("transform", "translate(0," + (height) + ")");

svg.append("g")
.attr("class", "minorTicks")
.attr("transform", "translate(0," + height + ")")
.call(xAxisMinorTicks)
.selectAll(".tick")
.data(x.ticks(52), function(d) { return d; })
.exit()
.classed("minorTicks", true);

svg.append("g")
.attr("class", "grid")
.attr("transform", "translate(0," + height + ")")
.call(xAxisMinor)
.selectAll(".tick")
.data(x.ticks(12), function(d) { return d; })
.exit()
.classed("minor", true);

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll(".tick text")
.style("text-anchor", "start")
.attr("x", 12)
.attr("y", 12);


// Vertical line for today

var theDate = new Date();
var today = theDate.getMonth()+1 + "/" + theDate.getDate() + "/" +     theDate.getFullYear();

svg.append("svg:line")
.attr("class", "today")
.attr("x1", x(d3.time.format("%x").parseDate(today)))
.attr("y1", height)
.attr("x2", x(d3.time.format("%x").parseDate(today)))
.attr("y2", 0);

1 个答案:

答案 0 :(得分:4)

在您的代码中,您只需更改下面的代码,

svg.append("svg:line")
.attr("class", "today")
.attr("x1", x(d3.time.format("%x").parseDate(today)))
.attr("y1", height)
.attr("x2", x(d3.time.format("%x").parseDate(today)))
.attr("y2", 0);

svg.append("svg:line")
    .attr("class", "today")
    .attr("x1", x(theDate))
    .attr("y1", height)
    .attr("x2", x(theDate))
    .attr("y2", 0);

d3.time.format("%x")这将返回一个函数,该函数将date对象作为参数,并返回%x格式的日期字符串。 但是你正在调用不可用/定义的parseDate函数。 Refer this

希望你得到它,如果不再问我更多。