charges.js 2.04 KB
const margin = {top: 150, right: 40, bottom: 10, left: 40},
    width = 1000 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

const tooltip_offset = {dx: 300, dy: 120}

const x = d3.scaleBand()
    .range([0, width])
    .padding(0.2);

const y = d3.scaleLinear()
    .range([height, 0]);

var color = d3.scaleOrdinal()
    .range([
        "#800000",
        "#FFFF00",
        "#808000",
        "#00FF00",
        "#008000",
        "#00FFFF",
        "#008080",
        "#0000FF",
        "#000080",
        "#FF00FF",
        "#800080",
    ]);

function build_chart(div_selector, data_url) {

    const svg = d3.select(div_selector).append("svg")
        .attr("id", "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(data_url).then(data => {
        var services = data.columns.slice(1)
        var periods = d3.map(data, d => d.period)

        console.log(data)

        var stack = d3.stack()
            .keys(services)
        // .order(d3.stackOrderNone)
        // .offset(d3.stackOffsetNone);
        var stacked_data = stack(data)

        // console.log(stacked_data)
        const x = d3.scaleBand()
            .domain(periods)
            .range([0, width])
            .padding(0.1);

        const y = d3.scaleLinear()
            .domain([0, 100])
            .range([height, 0]);


        let groups = svg.selectAll("g.category")
            .data(stacked_data)
            .enter()
            .append("g")
            .style("fill", (d) => color(d.key));

        let rect = groups.selectAll("rect")
            .data(d => d)
            .enter()
            .append("rect")
            .attr("x", d => x(d.data.period))
            .attr("width", x.bandwidth())
            // .attr("width", 5)
            .attr("y", d => y(d[1]))
            .attr("height", d => height - y(d[1] - d[0]))
            .attr("stroke", "black");

    });

}