我把这个条形图放在一起(滚动到右下角)
基于D3 的负值条形图示例
出于某种原因,文本标签显示在矩形后面。我该如何纠正?另外,我想让文本标签显示在条上,希望某些条对于文本来说太小不会成为问题。
var margin = {top: 30, right: 10, bottom: 10, left: 10},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.range([0, width])
var y = d3.scale.ordinal()
.rangeRoundBands([0, height], .2);
var xAxis = d3.svg.axis()
.scale(x)
.orient("top");
var svg = 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 + ")");
svg.selectAll("text")
.data(["asdf","DDdf","asdfsa"])
.enter().append("text").text(function(d) {
return d;
}).attr("y", function(d, i) {
return i * (height / ["asdf","asdf","asdfsa"].length)+30;
}).attr("x", function(d) {
return 0; //height - (d * 4);
}).text(String);
//d3.tsv("data.tsv", type, function(error, data) {
x.domain(d3.extent(data, function(d) { return d.netdonations_over_population_to_gdppercap_percentage; })).nice();
y.domain(data.map(function(d) { return d.name; }));
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", function(d) { return d.netdonations_over_population_to_gdppercap_percentage < 0 ? "bar negative" : "bar positive"; })
.attr("x", function(d) { return x(Math.min(0, d.netdonations_over_population_to_gdppercap_percentage)); })
.attr("y", function(d) { return y(d.name); })
.attr("width", function(d) { return Math.abs(x(d.netdonations_over_population_to_gdppercap_percentage) - x(0)); })
.attr("height", y.rangeBand());
svg.append("g")
.attr("class", "x axis")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.append("line")
.attr("x1", x(0))
.attr("x2", x(0))
.attr("y2", height);
}
//});
function type(d) {
d.value = +d.netdonations_over_population_to_gdppercap_percentage;
return d;
}