How do I add an “average” line to an nvd3.js Stacked Area Chart?

落花浮王杯 提交于 2019-12-06 02:57:22

Two other options:
1. Quick but a little hacky, create another line in your data for each average line by setting the same y value for each x value. You'll get a straight line although each x tick will have a tooltip with the same average value.
2. Draw a fixed line across the chart from the point where the average is on the yAxis:

//margin from chart declaration
var margin = { top: 30, right: 60, bottom: 60, left: 100 };
//calculate the yScale
var yScale = chart.yAxis.scale();
//call generic function...since you'll want this on potentially multiple types of charts
drawFixedLineAndText(chartID, 960, margin, <your average value goes here>, yScale, <your average label text goes here>);

function drawFixedLineAndText(chartName, width, margin, yValue, yValueScale, text) {
var svg = d3.select("#" + chartName + " svg");
svg.append("line")
    .style("stroke", "#FF7F0E")
    .style("stroke-width", "2.5px")
    .attr("x1", margin.left)
    .attr("y1", yValueScale(yValue) + margin.top)
    .attr("x2", width - margin.right)
  .attr("y2", yValueScale(yValue) + margin.top);


//add text to fixed line
d3.select("#" + chartName + " svg")
    .append("text")
    .attr("x", width - margin.right / 2)
    .attr("y", yValueScale(yValue) + margin.top)
    .attr("text-anchor", "middle")
    .text(text);
//end fixed line
}

It can be done in D3. Calculate average for the line while processing area data:

var line = d3.svg.line().interpolate("basis").x(function(d) {
    return x(d.x_axis);
}).y(function(d) {
    return y(d.y_axis);
});
var stacked_data = [];
var line_data = [];
data.forEach(function(d) {
    var total = 0;
    for (var i = 0; i < AREAS.length; i++) {
        var nd = {};
        nd.date = X_DATA_PARSE(d.date);
        nd.key = AREAS[i];
        nd.value = +d[AREAS[i]];
        stacked_data.push(nd);
        total = total + nd.value;
    }
    var ld = {};
    ld.x_axis = X_DATA_PARSE(d.date);
    ld.y_axis = total / AREAS.length;
    line_data.push(ld);
});

Then draw the line like normal line chart:

svg.append("path")
  .datum(line_data)
  .attr("class", "line")
  .attr("d", line);

Here's a complete example:

http://vida.io/documents/jXKmv3j3gF9LmtiyW

You can use nvD3 multichart option to achieve it. https://github.com/novus/nvd3/blob/master/examples/multiChart.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!