[英]Turn simple bar chart into Grouped Bar Chart (D3)
I have two data columns in my csv file named "profit" and "revenue".我的 csv 文件中有两个数据列,名为“profit”和“revenue”。 Currently, I am displaying only "profit" as a Simple Bar Chart.
目前,我仅将“利润”显示为简单条形图。 However, I wish to group the other column of data ie "revenue" along with "profit" and turn it into a Grouped Bar Chart.
但是,我希望将另一列数据(即“收入”)与“利润”一起分组,并将其转换为分组条形图。
Here is my csv data:这是我的 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
And here is my code on Plunker:这是我在 Plunker 上的代码:
https://plnkr.co/edit/rmGGbNwg4mEGLrXT?preview https://plnkr.co/edit/rmGGbNwg4mEGLrXT?preview
I would appreciate it if somebody could help me with this.如果有人可以帮助我,我将不胜感激。 Thanks in advance!
提前致谢!
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
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.