D3.js grouped bar chart

后端 未结 1 487
旧时难觅i
旧时难觅i 2021-01-07 09:04

I am making a bar chart using D3.js like this
(source: statcan.gc.ca)

but it is supposed to be vertical. so I can show comparison through two sets o

1条回答
  •  北荒
    北荒 (楼主)
    2021-01-07 09:12

    Edit: Got it. You left out the names of the second set of variables in 3 places:

    1.

    var chart2 = d3.select(".chart") (should be chart2)

    2.

    .attr("height", barHeight * data.length); (should be data2)

    3.

    var bar2 = chart.selectAll("g") (should be chart2)

    Will leave what I did with the placing below. Note the position:absolute on chart to make chart2 overlap with it.

    Your code has a couple problems, I just copied the part that works and made the changes to the data. I'll try to find all the issues in your code and edit my answer.

    For now, here's a working solution. I think what causes problem is some naming confusion so I just overwrite the same variables for both charts. Once svg elements have been appended you don't really need to keep the variables around.

    var data = [4, 8, 15, 16, 23, 42];
    
    
    var width = 420,
        barHeight = 80;
    
    var x = d3.scale.linear()
        .domain([0, d3.max(data)])
        .range([0, width]);
    
    
    var chart = d3.select(".chart")
        .attr("width", width)
        .attr("height", barHeight * data.length);
    
    
    var bar = chart.selectAll("g")
        .data(data)
        .enter().append("g")
        .attr("transform", function(d, i) { return "translate(0," + i * barHeight +")"; });
    
    bar.append("rect")
        .attr("width", x)
        .attr("height", barHeight - 60);
    
    var data = [10, 10, 10, 10, 10, 10];
    
    
    var width = 420,
        barHeight = 80;
    
    var chart = d3.select(".chart2")
        .attr("width", width)
        .attr("height", barHeight * data.length);
    
    
    var bar = chart.selectAll("g")
        .data(data)
        .enter().append("g")
        .attr("transform", function(d, i) { return "translate(0," + (i * barHeight + barHeight - 60 )  +")"; });
    
    bar.append("rect")
        .attr("width", x)
        .attr("height", barHeight - 60);
    

    http://jsfiddle.net/x8rax/6/

    0 讨论(0)
提交回复
热议问题