在不知道箱数的情况下在D3中绘制直方图

时间:2017-03-11 21:10:12

标签: javascript d3.js

我试图创建一个为给定数组创建直方图的函数。很明显,X轴没有数据,我必须任意选择箱子。最好的方法是什么?

我的代码:

var width = 700, height = 500, pad = 30, barPadding = 1;

        function plotHistogram(element, dataset) {

            var svg = d3.select(element)
                        .append("svg")
                        .attr("width", width)
                        .attr("height", height)

            var bars = svg.append("g")


            // Container box
            var rectangle = svg.append("rect")
                            .attr("height", height)
                            .attr("width", width)
                            .attr("stroke-width", 2).attr("stroke", "#ccc")
                            .attr("fill", "transparent")

            var xScale = d3.scaleLinear()
                    // Using default domain (0 - 1)
                    .range([pad, width - pad * 2])

            var yScale = d3.scaleLinear()
                            .domain([0, d3.max(dataset, function(d) { return d; })])
                            .range([height - pad, pad])

            var xAxis = d3.axisBottom(xScale)
            var yAxis = d3.axisLeft(yScale)

            svg.append("g")
                .attr("class", "axis")
                .attr("transform", "translate(0," + (height - pad) + ")")
                .call(xAxis)

            svg.append("g")
                .attr("class", "axis")
                .attr("transform", "translate(" + pad +", 0)")
                .call(yAxis)

            svg.selectAll("bars")
                .data(dataset)
                .enter()
                    .append("rect")

                    // Evenly spacing out bars
                    .attr("x", function(d, i) { return i * width/dataset.length; })

                    // Top of each bar as the top of svg. To remove inverted bar graph.
                    .attr("y", function(d) { return height - (d * 4); })

                    // To give padding between bars
                    .attr("width", width / dataset.length - barPadding)

                    // To make the bars taller
                    .attr("height", function(d) { return d * 4; })
                    .attr("fill", "teal");


        }
        // #normal is the id of the div element.
        plotHistogram("#normal", [10, 20, 30, 40, 50, 60, 70, 80]);

编辑1:我决定使用上面xScale的默认bin大小(0 - 1)。我在创建酒吧时遇到了问题。

1 个答案:

答案 0 :(得分:0)

按照https://bl.ocks.org/mbostock/3048450

生成垃圾箱

plotHistogram中的数组就像@ mbostock的bl.ock中的数组data ...

HTH