水平堆积条形图

时间:2015-08-21 01:49:19

标签: javascript d3.js

我正在尝试制作一个从左到右的堆积条形图。现在,由于我对计算机上的图形系统并不熟悉,我对间距等方面存在一些问题。

这是我的代码:

var canvas = d3.select("#canvas");
canvas.width = 500;
canvas.height = 500;

//rectangle values
var values = [{
    cValue: Math.abs(xthree),
    color: '#A0F'
}, {
    cValue: Math.abs(xtwo),
    color: '#FA0'
}, {
    cValue: Math.abs(xone),
    color: '#0AF'
}, {
    cValue: Math.abs(xzero),
    color: '#AF0'
}];

//var colours = ['#A0F', '#FA0', '#0AF', '#AF0'];

var yOffset = 0;

//create scale
//yRange2 = d3.scale.linear().range([canvas.height - MARGINS.top,
//MARGINS.bottom]).domain([0, 10]);

//yrange2- imp-Set domain to be set to biggest number
yRange2 = d3.scale.linear()
    .domain([0, 10])
    .range([MARGINS.bottom, canvas.height - MARGINS.top]);

//Process the data

for (var i = 0; i < values.length; i++) {

    var datum = {

        value: yRange2(values[i].cValue),
        colour: values[i].color,
        y: 0,
        x: yOffset

    }

    yOffset += (canvas.height - MARGINS.top - datum.value);

    data.push(datum)
}

//setup y
yAxis2 = d3.svg.axis()
    .scale(yRange2)
    .tickSize(5)
    .orient("bottom")
    .tickSubdivide(true);

canvas.append("svg:g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + (3 * MARGINS.bottom) + ")")
    .call(yAxis2);

var bars = canvas.selectAll('rect').data(data)

var cumValues = 0;
bars
    .enter()
    .append('rect')
    .attr("class", "myBars" + function (d) {
        return d.colour;
    })
    .attr({
        height: 30,
        y: 20,
        x: function (d) {
            return d.value - d.x; <-----------------------------------
        },
        width: function (d) {
            return canvas.width - MARGINS.left - d.value; <-----------
        }
    })
    .style({
        fill: function (d) {
            return d.colour
        }
    });

现在,我对矩形的放置方式存在问题,我已在代码中突出显示。

Here's the full code

1 个答案:

答案 0 :(得分:0)

必须完全重新定义导致属性定义的等式。我使用了以下,完美的工作:

.rtf
     for (var i = 0; i < values.length; i++) {

        var datum = {

            value: yRange2(values[i].cValue),
            colour: values[i].color,
            y: 0,
            x: yOffset

        }

        yOffset += (datum.value);
        data.push(datum)
    }