What is the best way to include an "average" line in a nvd3.js Stacked Area Chart?

My Stacked Area Chart is up and running smoothly using NVD3.js. You can view it in action on this working jsfiddle link.

var volumeData = [{"key":"Hit","values":[[1.3781628E12,12],[1.3782492E12,9],[1.3783356E12,9],[1.378422E12,4],[1.3785084E12,2],[1.3785948E12,3],[1.3786812E12,6],[1.3787676E12,5],[1.378854E12,1],[1.3789404E12,5],[1.3790268E12,1],[1.3791132E12,3],[1.3791996E12,0],[1.379286E12,2],[1.3793724E12,0]]},{"key":"Miss","values":[[1.3781628E12,3],[1.3782492E12,3],[1.3783356E12,1],[1.378422E12,12],[1.3785084E12,4],[1.3785948E12,7],[1.3786812E12,10],[1.3787676E12,13],[1.378854E12,14],[1.3789404E12,8],[1.3790268E12,5],[1.3791132E12,2],[1.3791996E12,3],[1.379286E12,11],[1.3793724E12,6]]}];


(function(data){
    var colors = d3.scale.category20();
    keyColor = function(d, i) {return colors(d.key)};

    var chart;
    nv.addGraph(function() {
        chart = nv.models.stackedAreaChart()
        .x(function(d) { return d[0] })
        .y(function(d) { return d[1] })
        .color(keyColor);

        chart.xAxis.tickFormat(function(d) { return d3.time.format('%x')(new Date(d)) });

        chart.yAxis.tickFormat(d3.format('d'));

        d3.select('#graph svg')
        .datum(data)
        .transition().duration(0)
        .call(chart);

        //nv.utils.windowResize(chart.update);

        return chart;
    });
})(volumeData);

I have a plan to include an "average" line for each series within the visible x-range. The calculations are not an issue, but I'm unsure how to display the line on the graph.

Would it be possible with nvd3.js, or would I need to switch to d3 for this task?

Answer №1

Here are two additional options to consider:
1. A quick workaround is to create extra data lines with the same y value for each x value, resulting in a straight line with tooltips displaying the average value.
2. You can draw a fixed line on the chart starting from the average point on the yAxis:

//Declare margin within the chart
var margin = { top: 30, right: 60, bottom: 60, left: 100 };
//Calculate yScale
var yScale = chart.yAxis.scale();
//Invoke a generic function for potential use across different chart types
drawFixedLineAndText(chartID, 960, margin, <insert your average value here>, yScale, <insert your average label text 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);


//Include text along the 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 of fixed line
}

Answer №3

If you're working with D3, you can easily calculate the average for a 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);
});

After that, you can draw the line like you would in a normal line chart:

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

If you want to see a complete example, check out this link:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The `mouseenter` event handler fails to trigger properly on its initial invocation

As I work on a function to remove a CSS class display:hidden; when the mouse enters a specific part of the DOM to reveal a menu, I encounter an issue. Upon loading the page and hovering over the designated area for the first time, the event fails to trigge ...

An error occurred with the authorization headers when attempting to retrieve the requested JSON

I am attempting to retrieve JSON data from the Bing Search API. Here is what I have implemented: <!DOCTYPE html> <html> <body> <p id="demo"></p> <script language="JavaScript" type="text/javascript" src="jquery-1.12.3.js"& ...

Finding All Initial Table Cells in jQuery

Is there a streamlined method for retrieving all td elements (cells) from every row within a specific table, or do I have to manually iterate through the collection myself? ...

Content within the Iframe is in the process of loading, followed by

Exploring the code below: <iframe id="myframe" src="..."></iframe> <script> document.getElementById('myframe').onload = function() { alert('myframe is loaded'); }; </script> Is it a possibility that the ifra ...

When a specific function is called, the DayPickerRangeController in the airbnb/react-dates library will update the

Is it possible to dynamically set the visible month in DayPickerRangeController after the component has been rendered? I have a 'handleMonthChange' function that I want to use to change the visible month, but setting 'initialVisible' mo ...

Using the .each() method in jQuery to dynamically assign an attribute to a parent element in JavaScript

I'm new to JavaScript and jQuery and I need help transitioning my code from jQuery to pure JS. Within my HTML, there are multiple parent divs each containing a child div. My goal is to assign a class to both the child and parent elements, with the p ...

What is the most effective way to transmit a conditional operator via a TypeScript boolean field?

Currently, as part of my transition to typescript, I am working on incorporating a conditional operator into the table component provided by Ant Design. const paginationLogic = props.data.length <= 10 ? false : true return ( <> ...

A step-by-step guide on enhancing error message handling for Reactive forms in Angular

Here is a code snippet that I'm working on: public errorMessages; ngOnInit(): void { this.startErrorMessage(); } private startErrorMessage() { this.errorMessages = maxLength: this.translate.instant(' ...

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...

Update the pageExtensions setting in Next.js to exclude building pages with the file extension *.dev.*

I am currently working on a project using Next.js version v12.3, and I have encountered an issue related to excluding page files with a *.dev.* extension from the build process. In my configuration file next.config.js, I have configured the pageExtensions ...

Looking for assistance in showcasing information retrieved from an external API

I've been working with an API and managed to fetch some data successfully. However, I'm having trouble displaying the data properly in my project. Can anyone provide assistance? Below is a screenshot of the fetched data from the console along wit ...

TypeScript React Object.assign method return type

I have a unique custom function that utilizes Object.assign to return a specific result. The documentation mentions that this function returns an array, but surprisingly, it can be destructured both as an array and an object. Check out the code snippet be ...

Can I employ a PHP script as a "server" for a React application?

As I am using shared hosting without Node installed, I can't utilize Express as a server (or any other node-related features xD). The issue arises when fetching data from the Behance API in my app and encountering a CORS error. To address this probl ...

What is the best way to transfer a request parameter from a URL to a function that generates an object with matching name in JavaScript?

I need to figure out how to pass a request parameter from an express router request to a function that should return an object with the same name. The issue I'm facing is that the function is returning the parameter name instead of the object. Upon c ...

Can you clarify the purpose of response.on('data', function(data) {}); in this context?

I am curious about the inner workings of response.on("data"). After making a request to a web server, I receive a response. Following that, I utilize response.on("data" ...); and obtain some form of data. I am eager to uncover what kind of data is being p ...

Ways to ensure CSS affects icon inside main element?

Struggling to match the background color of Material-UI icons with the rest of the list items on hover. The CSS is not applying to both the icon and text despite styling the overall class (className= "dd-content-item"). Any assistance would be greatly appr ...

Having trouble with the active class in vue-router when the route path includes "employees/add"?

I'm currently developing a project using Vue and implementing vue-router for navigation. A peculiar behavior occurs when the route changes to /employees - only the Employees menu item is activated. However, when the route switches to /employees/add, b ...

Enhancing UI-Grid: Implementing Dynamic Field Addition in the Header Name Section

There is a grid with a field named Users, and the requirement is to display the count of Users in the header name of a ui-grid. How can I achieve this? This snippet shows my JavaScript file code: var userCount = response.usercount; columnDefs: [{ nam ...

Exploring arrays and objects in handlebars: A closer look at iteration

Database Schema Setup var ItemSchema = mongoose.Schema({ username: { type: String, index: true }, path: { type: String }, originalname: { type: String } }); var Item = module.exports = mongoose.model('Item',ItemSchema, 'itemi ...

Transferring variables from the $(document).ready(function(){}) to the $(window).load(function(){} allows for seamless and

Just think about if I successfully create percent_pass at the time of document.ready, how can I transfer that variable to window.load? $(document).ready(function() { jQuery(function() { var ques_count = $('.question-body').length; va ...