d3 v3-具有单个堆叠条形图的分组条形图

时间:2019-08-28 16:03:14

标签: d3.js

在d3 v3中,我具有以下带有线条的分组条形图:

function draw(data) {

            console.log(data)
            //alert(data);

            var margin = { top: 20, right: 30, bottom: 60, left: 40 },
                width = 960 - margin.left - margin.right,
                height = 500 - margin.top - margin.bottom;

            var textWidthHolder = 0;
            /// Adding Date in LineCategory
            data.forEach(function (d) {
                d.LineCategory.forEach(function (b) {
                    b.Date = d.Date;
                })
            });

            var Categories = new Array();
            // Extension method declaration

            Categories.pro

            var x0 = d3.scale.ordinal()
                .rangeRoundBands([0, width], .1);
            var XLine = d3.scale.ordinal()
                .rangeRoundPoints([0, width], .1);
            var x1 = d3.scale.ordinal();

            var y = d3.scale.linear()
                .range([height, 0]);

            var YLine = d3.scale.linear().range([height, 0])
                .domain([0, 101]);

            var YLine2 = d3.scale.linear().range([height, 0])
                .domain([0, d3.max(data, function (d) { return d3.max(d.LineCategory, function (b) { return b.Value }) }) + 0.01]);

            var color = d3.scale.ordinal()
                .range(["#0b4a72", "#ad1a2c", "#7aa74d", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

            var line = d3.svg.line().x(function (d) {
                return x0(d.Date) + x0.rangeBand() / 2;
            }).y(function (d) { return YLine2(d.Value) });


            var xAxis = d3.svg.axis()
                .scale(x0)
                .orient("bottom");

            var yAxis = d3.svg.axis()
                .scale(y)
                .orient("left")
                .tickFormat(d3.format(".2s"));

            var YLeftAxis = d3.svg.axis().scale(YLine).orient("right").tickFormat(d3.format(".2s"));

            var div = d3.select("body").append("div")
                .attr("class", "tooltip")
                .style("opacity", 0);

            var svg = d3.select("#chart").append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

            // Bar Data categories
            data.forEach(function (d) {
                d.Categories.forEach(function (b) {
                    if (Categories.findIndex(function (c) { return c.Name === b.Name }) == -1) {
                        b.Type = "bar";
                        console.log(JSON.stringify(b))
                        Categories.push(b)
                    }
                })
            });


            // Line Data categories
            data.forEach(function (d) {
                d.LineCategory.forEach(function (b) {
                    if (Categories.findIndex(function (c) { return c.Name === b.Name }) == -1) {
                        b.Type = "line";
                        console.log(JSON.stringify(b))
                        Categories.push(b)
                    }
                })
            });

            // Processing Line data
            var lData = data.map(function (d) { return d.LineCategory });
            lineData = DataSegregator(lData, "Name");

            // Line Coloring
            LineColor = d3.scale.ordinal();
            LineColor.domain(Categories.filter(function (d) { return d.type == "line" }).map(function (d) { return d.Name }));
            LineColor.range(["#ff9933", "#cc33ff"])
            x0.domain(data.map(function (d) { return d.Date; }));
            XLine.domain(data.map(function (d) { return d.Date; }));
            x1.domain(Categories.filter(function (d) { return d.Type == "bar" }).map(function (d) { return d.Name })).rangeRoundBands([0, x0.rangeBand()]);
            y.domain([0, d3.max(data, function (d) { return d3.max(d.Categories, function (d) { return d.Value; }); })]);
            var formatDecimal = d3.format(".2f");
            var formatPercent = d3.format(".1%");

            svg.append("g")
                .attr("class", "x axis")
                .attr("transform", "translate(0," + height + ")")
                .attr("font-size", "10px")
                .call(xAxis);

            svg.append("g")
                .attr("class", "y axis")
                .attr("transform", "translate(" + (width) + ",0)")
                .call(YLeftAxis)

                .append("text")
                .attr("transform", "rotate(-90)")
                .attr("y", -10)

                .attr("dy", ".71em")
                .attr("font-size", "10px")
                .style("text-anchor", "end")
                .text("Percent");

            svg.append("g")
                .attr("class", "y axis")
                .call(yAxis)
                .append("text")
                .attr("transform", "rotate(-90)")
                .attr("y", 6)
                .attr("dy", ".71em")
                .attr("font-size", "10px")
                .style("text-anchor", "end")
                .text("Hours");


            var state = svg.selectAll(".state")
                .data(data)
                .enter().append("g")
                .attr("class", "state")
                .attr("font-size", "10px")
                .attr("transform", function (d) { return "translate(" + x0(d.Date) + ",0)"; });

            state.selectAll("rect")
                .data(function (d) { return d.Categories; })
                .enter().append("rect")
                .attr("width", x1.rangeBand())
                .attr("x", function (d) { return x1(d.Name); })
                .attr("y", function (d) { return y(d.Value); })
                //.attr("height", function (d) { return height - y(d.value); })
                .style("fill", function (d) { return color(d.Name); })
                .transition().delay(500).attrTween("height", function (d) {
                    var i = d3.interpolate(0, height - y(d.Value));
                    return function (t) {
                        return i(t);
                    }
                });

            state.selectAll("text")
                .data(function (d) { return d.Categories; })
                .enter().append("text")
                .text(function (d) { return formatDecimal(d.Value); })
                .attr("width", x1.rangeBand())
                .attr("x", function (d) { return x1(d.Name) + (x1.rangeBand() / 2); })
                .attr("y", function (d) { return y(d.Value) + 20; })
                .attr("text-anchor", "middle")
                .attr("font-family", "sans-serif")
                .attr("font-size", "10px")
                .attr("fill", "white");

            // drawaing lines
            svg.selectAll(".lines")
                .classed('labels-group', true)
                .data(lineData)
                .enter()
                .append("g")
                .attr("class", "line")
                .each(function (d) {
                    Name = d[0].Name;
                    d3.select(this)
                        .append("path")
                        .attr("d", function (b) { return line(b) })
                        .style({ "stroke-width": "3px", "fill": "none" })
                        .style("stroke", LineColor(Name))
                        .transition().duration(1500);

                    var texts = d3.select(this).selectAll('text.value')
                        .data(d)
                        .enter().append('text')
                        .classed('label', true)
                        .attr('dy', '-1em')
                        .attr("font-size", "12px")
                        .text(function (d) {
                            return formatPercent(d.Value);
                        })
                        .attr({
                            'x': function (d, i) {
                                var width = d3.select(this).node().getBBox().width;
                                return x0(d.Date) + x0.rangeBand() / 2 - width / 2;
                            },
                            'y': function (d, i) {
                                return YLine2(d.Value);
                            }
                        });

                    var dots = d3.select(this).selectAll(".dot")
                        .data(d)
                        .enter().append("circle") // Uses the enter().append() method
                        .attr("class", "dot") // Assign a class for styling
                        .attr("cx", function (d, i) { var width = d3.select(this).node().getBBox().width; return x0(d.Date) + x0.rangeBand() / 2 - width / 2; })
                        .attr("cy", function (d) { return YLine2(d.Value); })
                        .attr("r", 5)
                        .style("fill", LineColor(Name))
                        .on("mouseover", function (d) {
                            div.transition()
                                .duration(200)
                                .style("opacity", .9);
                            div.html(d.Name + "<br/>" + d.Date + "<br/>" + formatPercent(d.Value))
                                .style("left", (d3.event.pageX) + "px")
                                .style("top", (d3.event.pageY - 28) + "px");
                        })
                        .on("mouseout", function (d) {
                            div.transition()
                                .duration(500)
                                .style("opacity", 0);
                        });
                })



            // Legends

            var LegendHolder = svg.append("g").attr("class", "legendHolder");
            var legend = LegendHolder.selectAll(".legend")
                .data(Categories.map(function (d) { return { "Name": d.Name, "Type": d.Type } }))
                .enter().append("g")
                .attr("class", "legend")
                .attr("transform", function (d, i) { return "translate(0," + (height + margin.bottom / 2) + ")"; })
                .each(function (d, i) {
                    //  Legend Symbols


                    d3.select(this).append("rect")
                        .attr("width", function () { return 18 })
                        .attr("x", function (b) {

                            left = (i + 1) * 15 + i * 18 + i * 26 + textWidthHolder;
                            return left;
                        })
                        .attr("y", function (b) { return b.Type == 'bar' ? 0 : 7 })
                        .attr("height", function (b) { return b.Type == 'bar' ? 18 : 5 })
                        .style("fill", function (b) { return b.Type == 'bar' ? color(d.Name) : LineColor(d.Name) });

                    //  Legend Text

                    d3.select(this).append("text")
                        .attr("x", function (b) {

                            left = ((i + 1) * 15 + (i + 1) * 18 + (i + 1) * 5 + textWidthHolder) + (i * 20);

                            return left;
                        })
                        .attr("y", 9)
                        .attr("dy", ".35em")
                        .attr("font-size", "10px")
                        .style("text-anchor", "start")
                        .text(d.Name);

                    textWidthHolder += getTextWidth(d.Name, "10px", "calibri");
                });


            // Legend Placing

            d3.select(".legendHolder").attr("transform", function (d) {
                thisWidth = d3.select(this).node().getBBox().width;
                return "translate(" + ((width) / 2 - thisWidth / 2) + ",0)";
            })
        }

已提出要求取下两个小节并将它们堆叠,而其余的则保留原样。是否可以只堆叠我的4条中的2条?我假设我可以使用“条形数据类别”来定位这些特定类别,但是在其他堆叠式条形教程中,我不确定如何在此处集成该代码。

0 个答案:

没有答案