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

后端 未结 2 626
礼貌的吻别
礼貌的吻别 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: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.

提交回复
热议问题