D3.js: calculate x-axis time scale for bar graph?

后端 未结 2 625
礼貌的吻别
礼貌的吻别 2021-01-06 13:05

I have the following dataset:

var data = [
  {
    \"air_used\": 0.660985, 
    \"datestr\": \"2012-12-01 00:00:00\", 
    \"energy_used\": 0.106402
  }, 
          


        
相关标签:
2条回答
  • 2021-01-06 13:45

    Expand your domain to be +1 and -1 month from the actual extent of your data. That will pad the graph with the extra months on either side and then update the bar width to add 2 to the count of data elements.

    var barRawWidth = width / (data.length + 2);
    

    See this fiddle: http://jsfiddle.net/reblace/aWJtJ/6/

    If you want to hide the lower and upper boundary months, you can hack it like this: http://jsfiddle.net/reblace/aWJtJ/7/ by just adding and subtracting 20 days instead of a whole month, but there are probably more elegant ways to do it.

    var xExtent = d3.extent(data, function(d) { return d.date; });
    var nxExtent = [d3.time.day.offset(xExtent[0], -20), d3.time.day.offset(xExtent[1], 20)];
    x.domain(nxExtent);
    
    0 讨论(0)
  • 2021-01-06 13:57

    As pointed out in the comments, I think the best approach is to use d3.scale.ordinal. Note that using it doesn't prevent you from using d3.time parsers, but you need to take into account the bar width to align the line with the bars.

    An example solution is here: http://jsfiddle.net/jcollado/N8tuR/

    Relevant code from the solution above is as follows:

    // Map data set to dates to provide the whole domain information
    var x = d3.scale.ordinal()
        .domain(data.map(function(d) {
            return d.date;
        }))
        .rangeRoundBands([0, width], 0.1);
    
    ...
    
    // Use x.rangeBand() to align line with bars
    var line = d3.svg.line()
        .x(function(d) { return x(d.date) + x.rangeBand() / 2; })
        .y(function(d) { return y(d.energy_used); });
    
    ...
    
    // Use x.rangeBand() to set bar width
    bars.enter().append("rect")
        .attr("class", "air_used")
        .attr("width", x.rangeBand())
        ...
    

    Note that date parsing code has been moved up to have d.date available when creating the x scale. Aside from that, d3.time statements have not been modified at all.

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