Question

I have a dataset that lists dates as follows:

var dataset = [
["1-2006", 20],
["3-2009", 90],
["11-2004", 50],
["5-2012", 33],
["4-2008", 95],
["4-2004", 12],
["7-2000", 44],
["5-2006", 67],
["6-2007", 21],
["3-2001", 88]
];

I am trying to map these dates to a time scale on the x Axis and create a simple scatterplot with D3.js. Is it possible to create a scatterplot using a dataset with date values in the format shown above? I tried to create a min date and max date for the domain of my x Axis that would fit all the dates found in my dataset. I am unsure if I'm on the right track and could not find other scatterplot examples using this date format.

I am trying to create some kind of working example using this dataset. I am new to programming so I appreciate your patience and any help is greatly appreciated. Here is the rest of the sample code I ended up with:

var w = 500;
var h = 300;
padding = 20;

var format = d3.time.format("%m-%Y"),
mindate = format(parseDate("01-2000")),
maxdate = format(parseDate("01-2015"));

var xScale = d3.time.scale()
                    .domain([mindate, maxdate])
                    .range([padding, w - padding * 2]);

var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function (d) {
return d[1];
})])
.range([0, h]);

var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);

svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function(d) {
    return xScale(d[0]);
       })
.attr("cy", function (d) {
return yScale(d[1]);
})
.attr("r", 2);
Was it helpful?

Solution

You've got a couple of small mistakes that prevented your code from working:

  • mindate, maxdate, parseDate - didn't work, I would suggest a little code reorganization, see code below
  • when interpreting data points, you should use xScale(parseDate(d[0])) instead of just xScale(d[0])

Here is complete code of your modified example, that should work:

var w = 500;
var h = 300;
var padding = 20;

var parseDate = d3.time.format("%m-%Y").parse;
var mindate = parseDate("01-2000"),
    maxdate = parseDate("01-2015");

var xScale = d3.time.scale()
    .domain([mindate, maxdate])
    .range([padding, w - padding * 2]);

var yScale = d3.scale.linear()
    .domain([0, d3.max(dataset, function (d) {
         return d[1];
    })])
    .range([0, h]);

var svg = d3.select("body")
    .append("svg")
    .attr("width", w)
    .attr("height", h);

svg.selectAll("circle")
    .data(dataset)
   .enter()
    .append("circle")
    .attr("cx", function(d) {
        return xScale(parseDate(d[0]));
    })
    .attr("cy", function (d) {
        return yScale(d[1]);
    })
    .attr("r", 2);    

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top