User Tools

Site Tools


d3js sample

d3-sample.js
        let margin = { top: 20, right: 42, bottom: 30, left: 42 }
        let width = 450 - margin.left - margin.right
        let height = 400 - margin.top - margin.bottom
 
        let dataset = [80, 100, 56, 120, 180, 30, 40, 120, 160]
        //let dataset = [1, 2, 3, 4, 5]
 
        //let svg = d3
        //    .select('#my-chart')
        //    .append("svg")
        //    .attr("width", width)
        //    .attr("height", height)
 
        let svg = d3
            .select("#my-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 + ")")
 
        let xScale = d3
                    .scaleLinear()
                        .domain([1, dataset.length + 1])
                        .range([0, width])
 
        let yScale = d3
            .scaleLinear()
                .domain([0, d3.max(dataset)])
                .range([height, 0])
 
        let barPadding = 5
        let barWidth = (width / dataset.length)
 
        let barChart = svg
            .selectAll("rect")
            .data(dataset)
            .enter()
            .append("rect")
                .attr("y", function(d) {
                    return yScale(d)
                })
                .attr("height", function(d) {
                    return height - yScale(d)
                })
                .attr("width", barWidth - barPadding)
                .attr("transform", function(d, i) {
                    let translate = [barWidth * i, 0]
                    return "translate("+ translate +")"
                })
                .attr("fill", "#fe7a42");
 
        let text = svg
                .selectAll("text")
                .data(dataset)
                .enter()
                    .append("text")
                        .text(function(d) {
                            return d
                        })
                        .attr("y", function(d, i) {
                            return yScale(d) - 3
                        })
                        .attr("x", function(d, i) {
                            return barWidth * i + 2
                        })
                        .attr("fill", "#0a0a0a")
        svg
          .append('g')
          .attr("transform", "translate(0," + height + ")")
          .call(d3.axisBottom(xScale))
        svg
          .append('g')
          .call(d3.axisLeft(yScale))