Creating a D3.js scatterplot with timeline using 'month-year' date values

前端 未结 1 1248
梦如初夏
梦如初夏 2021-01-21 04:14

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-20         


        
相关标签:
1条回答
  • 2021-01-21 04:49

    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.

    0 讨论(0)
提交回复
热议问题