Grouped Bar Chart Slice repeats the last value

Hi, I’ve made this from a template:

However as you can see the last group gets repeated at the very beginning once.
I don’t quite understand why.

If I slice it before, (i.e. feed it just 6 cats) it renders well.
This is obviously an easy solution, but I’d like to know why this approach that is used here:
Grouped Bar Chart / D3 / Observable does not work right for me.

Can someone tell me what I’m doing wrong?

Thanks a lot!!

Currently for the domain of the x scale, you have

let xDomain = d3.groupSort(data, D => d3.sum(D, d => -d.value), d => d.Category).slice(0, 6)

which results in ["Health / Wellness", "Media / Entertainment", "Automotive", "Travel", "Business Services", "Uncertain / Other"].

However, data and nestedData still contain all 14 categories, not just those 6. So when you do

 const rectangleGroups =  g.selectAll(".data-group")
          .data(nestedData)
        .enter().append("g")
          .attr("transform", d => `translate(${xScale(d[0])},0)`)

you are creating one group for each of the 14 categories. The x scale’s domain only contains 6 of those categories. When you pass xScale a category not in its domain, it returns undefined. So for the 8 groups whose category is not in the domain, their transform is set to "translate(undefined, 0)", which is causing them to appear at the start of the chart.

If you only want the grouped bar chart to show the first 6 categories, then you need to filter your data so that it only contains those 6 categories as well. For example, you could use this:

const nestedData = d3.group(data.filter(d => xDomain.includes(d.Category)), d => d.Category)
1 Like

Ah wonderful, thank you very much Daniel!