如何在D3中构建带有目标线的条形图?我尝试在条形图的顶部添加一条带有Target字段的行,但我想要实现的是类似于此:
这是我的表:
Country,Nitrogen2012,Target
Poland,0.22,0.213
Sweden,0.13,0.156
Russia,0.11,0.097
Finland,0.11,0.110
Latvia,0.08,0.076
Atmospheric,0.08,0.075
Germany,0.07,0.075
Denmark,0.07,0.088
Lithuania,0.06,0.050
Estonia,0.03,0.033
Shipping,0.02,0.003
条形图的代码是:
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 80
},
width = 900 - margin.left - margin.right,
height = 200 - margin.top - margin.bottom;
var formatPercent = d3.format(".0%");
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")
.tickSize(-1);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(2, "d")
.tickSize(-1)
.tickFormat(formatPercent);
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return "<strong>Average normalized input:</strong> <span style='color:red'>" + d.Nitrogen2012 * 100 + "</span>";
})
var chart1 = d3.select("#graph1").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 + ")");
chart1.call(tip);
d3.csv("Nitrogen_Inputs2012ComparedToTarget.csv", type, function(error, data) {
x.domain(data.map(function(d) {
return d.Country;
}));
//x2.domain(data.map(function(d){return d.Target}));
y.domain([0, d3.max(data, function(d) {
return d.Nitrogen2012
})]);
chart1.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
chart1.append("g")
.attr("class", "y axis")
.call(yAxis);
chart1.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) {
return x(d.Country);
})
.attr("width", x.rangeBand())
.attr("y", function(d) {
return y(d.Nitrogen2012);
})
.attr("height", function(d) {
return height - y(d.Nitrogen2012);
})
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
});
function type(d) {
d.Nitrogen2012 = +d.Nitrogen2012;
return d;
}
&#13;
有什么想法吗? 谢谢!
答案 0 :(得分:1)
在您的输入选择中,添加该行。您可以使用svg:line
执行此操作,但我更喜欢构建path
:
var eSel = chart1.selectAll(".bar")
.data(data)
.enter();
eSel.append("rect")
.attr("class", "bar")
...
eSel.append("path")
.style("stroke", "blue")
.style("stroke-width", 2)
.attr("d", function(d){
var rv = "M" + x(d.Country) + "," + y(d.Target); // move to
rv += "L" + (x(d.Country) + x.rangeBand()) + "," + y(d.Target); // line
return rv;
});
工作示例here。