将简单的条形图转换为分组条形图(D3)

Turn simple bar chart into Grouped Bar Chart (D3)

我的 csv 文件中有两个数据列,分别名为“利润”和“收入”。目前,我仅将“利润”显示为简单条形图。但是,我希望将另一列数据(即“收入”和“利润”)分组,并将其转换为分组条形图。

这是我的 csv 数据:

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

这是我在 Plunker 上的代码:

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

如果有人能帮助我,我将不胜感激。提前致谢!

好的,这是一个粗略的答案,但可以让您进一步开发您想要的东西。您只需要调整条形宽度即可每月容纳两个条形。 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")