我的 csv 檔案中有兩個資料列,名為“profit”和“revenue”。目前,我僅將“利潤”顯示為簡單條形圖。但是,我希望將另一列資料(即“收入”)與“利潤”一起分組,并將其轉換為分組條形圖。
這是我的 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/script.js&preview
如果有人可以幫助我,我將不勝感激。提前致謝!
uj5u.com熱心網友回復:
好的,這是一個粗略的答案,但可以讓您進一步開發您想要的東西。您只需要使用條形寬度即可每月容納兩個條形。 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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/419408.html
標籤:
