我正在尝试构建一个非常基本的条形图。三个酒吧。数据是正确的。但是,当我使用开发工具检查条形图时,条形图不会显示,也不会显示。但是,x轴和y轴正确渲染,带有正确的标签和刻度线。
function buildBarChart(data) {
var margin = {top: 20, right: 20, bottom: 30, left:40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
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 chart = d3.select(".barchart").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 + ")");
var mapped_values = _.map(data, function(d) {
return d.count;
});
x.domain(d3.keys(data));
y.domain([0, d3.max(mapped_values)]);
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
chart.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("Count");
_.each(data, function(d) {
console.log(d.name + " ++ " + (height - y(d.count)) + " ++ " + d.count);
});
chart.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.name) })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.count); })
.attr("height", function(d) { return height - y(d.count); });
};
上面的console.log的结果是:
quotes ++ 90 ++ 16
subscriptions ++ 450 ++ 80
sponsored_licenses ++ 45 ++ 8
这是正确的。我已经开始了几个小时,无法弄清楚为什么一切都会显示(包括同一页面上的折线图),除了酒吧。
为什么我的酒吧没有显示?
答案 0 :(得分:2)
分配给选区的数据必须是数组,而不是键:值对象。您可以使用d3.values(object)
实用程序功能仅将值提取为数组。
chart.selectAll(".bar")
.data(d3.values(data))
/* etc. */
但是,对象的键值不再以该形式提供,我注意到您将它们用于x轴。如果键与数据对象的“名称”相同,那应该不是问题。如果没有,d3.entries()
实用程序函数返回键和值,但值变为嵌套对象,因此您必须使用d.value.name
和d.value.count
访问原始数据。