how to create bar graph dynamically using d3 js in

2019-09-05 08:40发布

问题:

I am new in D3 js and working on it.i wanted to implement bar graph through it in my MVC3 web application.Could you please let me know how can i create bar graph with dynamically.below is sample code but i am not able to find the dynamic creation bar graph

<script>
    var margin = { top: 20, right: 20, bottom: 30, left: 50 },
        width = 600 - margin.left - margin.right,
        height = 400 - margin.top - margin.bottom;

    var parseDate = d3.time.format("%Y").parse;

    var x = d3.time.scale()
        .range([0, width]);

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

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

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    var line = d3.svg.line()
        .x(function (d) { return x(d.year); })
        .y(function (d) { return y(d.oil); });

    var svg = d3.select("body").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 + ")");

    d3.csv("YearlyOilProduction.csv", function (error, data)
    {
        data.forEach(function (d) {
            d.year = parseDate(d.year);
            d.oil = +d.oil;
        });


        x.domain(d3.extent(data, function (d) { return d.year; }));
        y.domain(d3.extent(data, function (d) { return d.oil; }));

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

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis)
            .append("text")
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", ".71em")
            .style("text-anchor", "end")
            .text("million Sm3");

        svg.append("path")
            .datum(data)
            .attr("class", "line")
            .attr("d", line);
    });

</script>