Search code examples
javascripthtmld3.jsdata-visualizationvisualization

Turn simple bar chart into Grouped Bar Chart (D3)


I have two data columns in my csv file named "profit" and "revenue". Currently, I am displaying only "profit" as a Simple Bar Chart. However, I wish to group the other column of data i.e "revenue" along with "profit" and turn it into a Grouped Bar Chart.

Here is my csv data:

month,revenue,profit
January,123432,80342
February,19342,10342
March,17443,15423
April,26342,18432
May,34213,29434
June,50321,45343
July,54273,80002

And here is my code on Plunker:

https://plnkr.co/edit/UaL3urb5L41uN1e2?open=lib%2Fscript.js&preview

I would appreciate it if somebody could help me with this. Thanks in advance!


Solution

  • Ok, this is a crude answer, but will allow you to further develop what you want. You just need to play with the bar widths in order to accommodate two bars per month. https://plnkr.co/edit/K9LVNpFPmXFIGufM?preview

            const rects = g.selectAll("rect.profit")
                .data(data)
    
            rects.exit().remove()
    
            rects
                .attr("y", d => y(d.profit))
                .attr("x", (d) => x(d.month))
                .attr("width", 0.5 * x.bandwidth())
                .attr("height", d => HEIGHT - y(d.profit))
    
            rects.enter().append("rect")
                .attr("class", "profit")
                .attr("y", d => y(d.profit))
                .attr("x", (d) => x(d.month))
                .attr("width", 0.5 * x.bandwidth())
                .attr("height", d => HEIGHT - y(d.profit))
                .attr("fill", "grey")
    
            const rects_revenue = g.selectAll("rect.revenue")
                .data(data)
    
            rects_revenue.exit().remove()
    
            rects_revenue
                .attr("y", d => y(d.revenue))
                .attr("x", (d) => x(d.month))
                .attr("width", 0.5 * x.bandwidth())
                .attr("height", d => HEIGHT - y(d.revenue))
    
            rects_revenue.enter().append("rect")
                .attr("class", "revenue")
                .style("fill", "red")
                .attr("y", d => y(d.revenue))
                .attr("x", (d) => x(d.month) + 0.5 * x.bandwidth())
                .attr("width", 0.5 * x.bandwidth())
                .attr("height", d => HEIGHT - y(d.revenue))
                .attr("fill", "grey")