【发布时间】:2021-10-09 02:20:08
【问题描述】:
我正在学习如何使用 D3.js,并且我正在尝试从我从外部 API 获取的 JSON 数据中呈现多个饼图。我正在使用的数据如下所示
tickers = [{
"symbol": "GME",
"buy": 0,
"hold": 3,
"period": "2021-08-01",
"sell": 5,
"strongBuy": 0,
"strongSell": 2
}, {
"symbol": "AMD",
"buy": 21,
"hold": 16,
"period": "2021-08-01",
"sell": 1,
"strongBuy": 8,
"strongSell": 0
}]
我正在尝试为数组中的每个对象呈现一个饼图,但我似乎无法将数据正确地流向我的饼图。我只想要每个饼图上的“强力卖出”、“卖出”、“持有”、“买入”和“强力买入”信息。
我尝试了以下代码,并附上了显示 HTML 和饼图的屏幕截图
var margin = 20, width = 250, height = 250
var radius = Math.min(width, height) / 2 - margin
var new_data = tickers.map(function(d){
if (d){
var temp = {"Strong Sell": d.strongSell, "Sell": d.sell, "Hold": d.hold, "Buy": d.buy, "Strong Buy": d.strongBuy}
} else {
var temp = {"Strong Sell": 0, "Sell": 0, "Hold": 0, "Buy": 0, "Strong Buy": 0}
}
return temp
})
var color = d3.scaleOrdinal()
.domain(["Strong Sell", "Sell", "Hold", "Buy", "Strong Buy"])
.range(["#570e00", "#ff2a00", "#ffff00", "#00ff08", "#00570c"])
var pie = d3.pie()
.value(function(d) {return d.value; })
var data_ready = pie(d3.entries(new_data))
var recommendSvg = d3.selectAll(".company-recommend")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
recommendSvg
.selectAll('g')
.data(data_ready)
.enter()
.append('path')
.attr('d', d3.arc()
.innerRadius(0)
.outerRadius(radius)
)
.attr('fill', function(d){ return(color(d.data.key)) })
.attr("stroke", "black")
.style("stroke-width", "2px")
.style("opacity", 0.7)
任何帮助或建议将不胜感激!
【问题讨论】:
标签: javascript d3.js charts pie-chart