javascript - Adding Error Bars to Grouped Bar Chart with D3.js -
first find out if knows of d3 example showing grouped bar charts error bars? closest things have found are:
http://tenxer.github.io/xcharts/examples/ (example custom vis type: error bars) http://bl.ocks.org/chrisbrich/5044999 (error bars points)
i have working example of grouped bar chart , add error bar each bar in graph showing moe. steps need take accomplish this? how calculate position of line? think needs done, please me fill in steps need take.
create svg line
calculate ymin , ymax of line taking d3.max of d.value + moe , d3.max of d.value - moe
append
this doesn't work on right track?
var line = d3.svg.line() .x(function(d) {return x(d.state); }) .y0(function(d) {return y(d.value - d.moe); }) .y1(function(d) {return y(d.value + d.moe); }) .interpolate("linear"); var errorbarsvg = d3.select("body").append("svg") var errorbar = errorbarsvg.append("path") .attr("d", line(data)) .attr("stroke", "red") .attr("stroke-width", 1.5);
if want straight-line error bars (without top , bottom horizontal lines), yes, use area or line generator (only area generators have y0/y1 methods).
however, wouldn't call path generator on data @ once, have create selection of paths joined data, , pass data object 1 (area generator) or two-point (line generator) array generator function.
this should work:
var errorbararea = d3.svg.area() .x(function(d) {return x(d.state); }) .y0(function(d) {return y(d.value - d.moe); }) .y1(function(d) {return y(d.value + d.moe); }) .interpolate("linear"); var errorbarsvg = d3.select("body").append("svg") var errorbars = errorbarsvg.selectall("path") .data(data); errorbars.enter().append("path"); errorbars.attr("d", function(d){return errorbararea([d]);}) //turn data one-element array //and pass area function .attr("stroke", "red") .attr("stroke-width", 1.5);
this create zero-width area path each bar, connecting +/- points in straight line.
if used line generator function, have calculate top , bottom y-values when turned data array:
errorbars.attr("d", function(d){ return errorbarline([{x:d.x, y:d.value - d.moe}, {x:d.x, y:d.value + d.moe}]); })
alternately, use d3.svg.diagonal
create straight-line error bars. diagonal function designed take single data object , extract start , end line points it; have customize source
, target
accessor functions create objects ones in code sample above.
however, if want custom-shaped error bar horizontal top , bottom lines, you'll need write own function create path "d"
attribute based on data object. discuss doing in this answer, error bar shape simpler, since it's straight lines. might find this tutorial on path directions syntax useful reference.
finally, might want re-write bar chart code each bar represented <g>
element joined data, , append both rectangle , error bar path within without calculating separate data joins.
Comments
Post a Comment