magritte
magritte

Reputation: 7646

Simple line graph with dates in D3

I'm trying to get to grips with D3 and want to draw a demo of a simple line graph with 7 days along the x-axis. So far I have 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));

I'm stuck with a few things:

Upvotes: 4

Views: 5954

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109282

I've updated your jsfiddle to do what you want here. Briefly I did the following:

  • Use a time scale instead of a linear scale. Then you can specify d3.time.days, 1 as ticks.
  • A path is filled by default with no stroke. See the CSS I've added.
  • Use the .tickFormat function with an appropriate format.
  • Should be fixed by using a time scale and appropriate tick spec.

Upvotes: 4

Related Questions