0
votes

I have a plunker here - https://plnkr.co/edit/avVtvdm8Q8tnClAqYxlH?p=preview

Its a bar chart showing two diiferent data points on each point of the x axis.

The bars have the same padding set in the xscale

var x = d3.scaleBand()
  .range([0, width])
  .padding(.33)
  .domain(data.map(function(d) { 
    return d.phase
  }));

Id like the green bars to have more padding and so be inside the red bars

How can I set different padding on the green bars.

1
I'm partly there but now I need to centre the green bars - plnkr.co/edit/avVtvdm8Q8tnClAqYxlH?p=previewttmt

1 Answers

1
votes

Here are two different approaches I can think of right away:

  1. Set an offset to define how much less should the inner bar width should be compared to the outer and adjust the bars accordingly.

    var offset = 10;
    chart.selectAll(".bar").attr("x", (d, i) => {
      return i%2 ? x(d.phase)+offset/2 : x(d.phase)
    })
    .attr("y", (d, i) => {
       return y(d.finish);
     })
    .attr("width", (d,i) => {
       return i%2 ? x.bandwidth()-offset : x.bandwidth();
    })
    

    Plunkr: https://plnkr.co/edit/2ZSKGmjj3ntJEA3KGq9e?p=preview

  2. Set a different scale for the green bars (I'd prefer this approach):

    var x1 = d3.scaleBand()
     .range([0, width])
     .padding(.56)
     .domain(data.map(function(d) { 
       return d.phase
    })); 
    

    And accordingly, change the bar attributes:

    chart.selectAll(".bar")
      .attr("x", (d, i) => {
        return i % 2 ? x(d.phase)+(Math.abs(x1.bandwidth()-x.bandwidth())/2) : x(d.phase)
      })
      .attr("y", (d, i) => {
        return y(d.finish);
      })
    
      .attr("width", (d, i) => {
        return i % 2 ? x1.bandwidth() : x.bandwidth()
      })
    

    The tricky part here would be setting the inner bar offset but you can clearly see the logic there: Difference between the bandwidths of the scales/2

    Plunkr:https://plnkr.co/edit/X5vFB99JBHkfGvSIfXAo?p=preview

Hope this helps.