如何使用D3从包含多个对象的单个数组生成多个饼图?
你代码的核心问题是没有将单条股票数据和对应的展示容器绑定,同时饼图生成器的数据输入格式错误。修正后的代码如下:
const margin = 20, width = 250, height = 250 const radius = Math.min(width, height) / 2 - margin // 颜色比例尺定义保持不变 const color = d3.scaleOrdinal() .domain(["Strong Sell", "Sell", "Hold", "Buy", "Strong Buy"]) .range(["#570e00", "#ff2a00", "#ffff00", "#00ff08", "#00570c"]) // 饼图生成器定义保持不变 const pie = d3.pie() .value(d => d.value) const arcGenerator = d3.arc() .innerRadius(0) .outerRadius(radius) // 步骤1:将股票数组数据绑定到对应的展示容器上 const recommendContainers = d3.selectAll(".company-recommend") .data(tickers) // 步骤2:为每个容器创建svg画布和居中分组 const recommendSvgGroups = recommendContainers .append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", `translate(${width/2}, ${height/2})`) // 步骤3:为每个分组单独渲染对应股票的饼图 recommendSvgGroups.each(function(d) { // 转换单条股票数据为饼图需要的格式 const ratingData = [ {key: "Strong Sell", value: d.strongSell}, {key: "Sell", value: d.sell}, {key: "Hold", value: d.hold}, {key: "Buy", value: d.buy}, {key: "Strong Buy", value: d.strongBuy} ] // 生成当前股票的饼图数据 const pieData = pie(ratingData) // 渲染扇形 d3.select(this) .selectAll('path') .data(pieData) .enter() .append('path') .attr('d', arcGenerator) .attr('fill', d => color(d.data.key)) .attr("stroke", "black") .style("stroke-width", "2px") .style("opacity", 0.7) })
补充说明:
- 请确保页面中
.company-recommend元素的数量和tickers数组的长度完全一致,否则会出现多渲染/少渲染饼图的问题 - 如果需要动态生成容器,可以用D3的enter()逻辑动态创建
.company-recommend元素,无需提前写死在HTML中
内容的提问来源于stack exchange,提问作者Taihuynh812
相关产品推荐
相关产品推荐

