1

我想在 d3.js 堆积条形图上显示 y 轴。我可以显示 x 轴,但不能显示 y 轴。

这是我的代码,但 y 轴从不显示。我肯定犯了一个错误,但我看不出在哪里。

var w = 600,
h = 500

var dataset = [
{"month":"JAN","purchased":6,"sold":3},
{"month":"FEV","purchased":7,"sold":5},
{"month":"MARS","purchased":4,"sold":3},
{"month":"AVR","purchased":4,"sold":2},
{"month":"MAI","purchased":8,"sold":1},
{"month":"JUIN","purchased":3,"sold":3},
{"month":"JUIL","purchased":3,"sold":4},
{"month":"AOU","purchased":4,"sold":2},
{"month":"SEPT","purchased":6,"sold":3},
{"month":"OCT","purchased":6,"sold":4},
{"month":"NOV","purchased":7,"sold":3},
{"month":"DEC","purchased":6,"sold":3}
];

var matrix = new Array();

$.each(dataset, function(i, item) {
var oneMonth = new Array();
oneMonth.push(dataset[i].month);
oneMonth.push(dataset[i].purchased);
oneMonth.push(dataset[i].sold);

matrix.push(oneMonth);
});

var remapped =["purchased","sold"].map(function(dat,i){
return matrix.map(function(d,ii){
    return {x: ii, y: d[i+1] };
})
});



var x = d3.scale.ordinal()
.domain(dataset.map(function (d) {return d.month; }))
.rangeRoundBands([ 0, w ], .4);

var y = d3.scale.linear()
.domain([0, 15])
.range([0, h-50]);

var z = d3.scale.ordinal().range(["#e01b5d", "#eda13e"]);

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

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


// create canvas
var svg = d3.select("#viz").append("svg:svg")
.attr("class", "chart")
.attr("width", w)
.attr("height", h )
.append("svg:g")
.attr("transform", "translate(10,470)")
.call(xAxis);

var stacked = d3.layout.stack()(remapped);

x.domain(stacked[0].map(function(d) { return d.x; }));
y.domain([0, d3.max(stacked[stacked.length - 1], function(d) { return d.y0 + d.y; })]);

// Add a group for each column.
var valgroup = svg.selectAll("g.valgroup")
.data(stacked)
.enter().append("svg:g")
.attr("class", "valgroup")
.style("fill", function(d, i) { return z(i); });

// Add a rect for each date.
var rect = valgroup.selectAll("rect")
.data(function(d){return d;})
.enter().append("svg:rect")
.attr("x", function(d) { return x(d.x); })
.attr("y", function(d) { return -y(d.y0) - y(d.y); })
.attr("height", function(d) { return y(d.y); })
.attr("width", x.rangeBand());

svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(20)")
.call(yAxis);

这是结果 结果

谢谢你的帮助

4

2 回答 2

1

看起来它正在下降到图表下方。

这是一个小提琴,我将其更改transform(20)transform(20, -h). 天平是颠倒的,但它就在那里。

于 2013-08-09T13:27:42.830 回答
0

我只是更新了一下肖恩的小提琴来制作

xAxis 

并且 yAxis 有效,我没有进一步讨论条形高度的计算,这里是小提琴

在此处输入图像描述

于 2014-10-21T06:06:57.510 回答