gpt4 book ai didi

javascript - D3 条形图到堆积条形图

转载 作者:行者123 更新时间:2023-11-29 16:07:23 24 4
gpt4 key购买 nike

大家好,我是 D3 的新手,我正在尝试将普通条形图转换为堆积条形图。

这是我的代码

var data = [4, 8, 15, 16, 23, 42, 200];

var height = 200;
var width = 200;
var barWidth = 35;
var barOffset = 5;

var myChart = d3.select(".chart").append('svg')
.attr('width', width)
.attr('height', height)
.style("background", "grey")
.selectAll('rect')
.data(data)
.enter().append('rect').
style("fill", "blue")
.attr("width", barWidth)
.attr("height", function(d){ return d;})
.attr('x', function(d, i)
{ return i *(barWidth + barOffset);})
.attr('y', function(d){
return height - d;
});

任何帮助或暗示正确的方向将不胜感激。

最佳答案

只是对以上答案的评论..

这是代码-

var data = [
[4, 8, 15, 16, 23, 42, 200],
[50, 60, 20, 100, 30, 50, 40]
];
//console.log(data)

//console.log("REMAP---------------------------");
var remapped =data[0].map(function(dat,i){
return data.map(function(d,ii){
return {x: ii, y: d[i] };
})
});


var w = 200,
h = 200

// create canvas
var svg = d3.select(".chart").append("svg:svg")
.attr("width", w)
.attr("height", h )
.append("svg:g")
.attr("transform", "translate(0,"+h+")");

var x = d3.scale.ordinal().rangeRoundBands([0, w], 0.5)
var y = d3.scale.linear().range([0, h])
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]).domain(data[0].map(function(d,i){return i;}));



//console.log("LAYOUT---------------------------");
var stacked = d3.layout.stack()(remapped)
//console.log(stacked)

x.domain(stacked[0].map(function(d) { return d.x; }));
y.domain([0, d3.max(stacked[stacked.length - 1], function(d) { return d.y0 + d.y; })]);

// show the domains of the scales
console.log("x.domain(): " + x.domain())
console.log("y.domain(): " + y.domain())


// Add a group for each column.
var valgroup = svg.selectAll("g.valgroup")
.data(stacked)
.enter().append("svg:g")
.attr("class", "valgroup")
.style("fill", function(d, i) { return color(i); })
.style("stroke", function(d, i) { return d3.rgb(color(i)).darker(); });

// Add a rect for each date.
var rect = valgroup.selectAll("rect")
.data(function(d){return d;})
.enter().append("svg:rect")
.attr("x", function(d) { return x(d.x); })
.attr("y", function(d) { return -y(d.y0) - y(d.y); })
.attr("height", function(d) { return y(d.y); })
.attr("width", x.rangeBand());
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

<div class="chart"></div>

关于javascript - D3 条形图到堆积条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37780717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com