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

Exploring the mocking of document,hidden using Jasmine

Struggling to simulate document.hidden in an angular unit test, but facing issues. Tried the following solutions: spyOn(Document.prototype, <any>'hidden').and.returnValue(true); spyOn(Document, <any>'hidden').and.ret ...

Deleting information from several stores in React Reflux using a single action function

In the AuthActions file, there is a straightforward function called _clear that assigns this.data to undefined. This function is only invoked when a user logs out. However, upon logging back in with a different user, remnants of data from the previous ac ...

Using Mongoose with Next.js to implement CRUD operations

I have been successful in implementing POST and GET methods in my Next.js app using mongoose, but I am facing challenges with the delete operation. This is an example of my POST method located in the API folder: export default async function addUser(req, ...

Executing JavaScript in Rails after dynamically adding content through AJAX

Looking for advice on integrating JavaScript functions into a Rails app that are triggered on elements added to the page post-load via AJAX. I've encountered issues where if I include the code in create.js.erb, the event fires twice. However, removing ...

Issue with React: Children's state is altering the state of the parent component

Question : Why is it possible for a child component to change the state of its parent when each component has its own state? Below is the complete code for my app: import React, { Component } from 'react'; import { render } from 'react-do ...

Troubleshooting the non-functioning addEventListener in JavaScript

I am facing an issue where a function that should be triggered by a click event is not working and the console.log message does not appear <script src="e-com.js" async></script> This is how I included the javascript file in the head ...

Parsing JSON data received from Angular using JSP

As I navigate through my Angular application, I'm encountering a challenge when trying to save data on the server side using JSP. The issue arises when Angular's $save method sends the object data in a JSON format that is not familiar to me. This ...

Error: Attempting to access properties of undefined object (reading 'hash') has caused an unhandled TypeError

I've been working on a project to store files in IPFS and then record the hash on the blockchain. However, I encountered an error message while trying to upload the file to IPFS. Error Message: Unhandled Rejection (TypeError): Cannot read properties ...

What causes the form to be submitted when the text input is changed?

I'm puzzled by the behavior of this code snippet that triggers form submission when the input value changes: <form> <input type="text" onchange="submit();"> </form> Typically, I would expect something along t ...

Utilize VueJS to pass back iteration values using a custom node extension

Hey there! I'm currently working on a Vue app that generates a color palette based on a key color. The palette consists of 2 lighter shades and 2 darker shades of the key color. To achieve this, I have set up an input field where users can enter a hex ...

Issue with React component not displaying in the browser.Here are some

I am currently following a React tutorial on and I'm facing an issue where the Counter component is not displaying on the page. The generated HTML looks like this: <html> <head> <script src="/bundle.js" ></script> </he ...

What steps can I take to ensure the browser only shows the page once it has completely loaded?

I find it frustrating when webpages load slowly and you can see the process happening. In my opinion, it would be more satisfying to wait until everything is fully loaded - scripts, images, and all - before displaying the page. This brings up two questio ...

Setting up a div as a canvas in Three.js: Step-by-step guide

Is there a way to adjust the JavaScript in this three.js canvas example so that the scene can be contained within a specific div element on a webpage? Here is the example: https://codepen.io/PedalsUp/pen/qBqvvzR I would like to use this as the background ...

Every time the page is refreshed, ExpressJS and NodeJS are working together to duplicate the array

var express = require("express"); var router = express.Router(); const fs = require("fs"); const path = require("path"); const readline = require('readline'); const directoryPath = path.resolve(__dirname,"../log ...

Tips for accessing the initial value within JSON curly braces

In my code, there is a function that returns the following: { 'random_string': '' } The value of random_string is an unknown id until it is returned. How can I extract this value in JavaScript? Appreciate any help. Thanks. ...

Can the performance of a system be impacted by node.js cron?

I am looking to incorporate a cron module (such as later or node-cron) into my node server for job scheduling. The jobs in question involve sending notifications (e.g., email) to remind users to update their profile picture if they haven't done so wit ...

Require that JSX elements begin on a new line if the JSX element spans multiple lines

Which eslint rule favors the first syntax over the second when JSX code spans multiple lines? Currently, Prettier is changing `preferred` to `notPreferred`. const preferred = ( <tag prop={hi} another={test} \> ); const ...

tips for setting the value of a checkbox to true in React Material-UI with the help of React Hooks

<FormControlLabel onChange={handleCurrentProjectChange} value="end" control={<Checkbox style={{ color: "#C8102E" }} />} label={ <Typography style={{ fontSize: 15 }}> C ...

The data being transmitted by the server is not being received accurately

Hey there! I've recently started using express.js and nodejs, but I've encountered an issue where my server is sending me markup without the CSS and JS files included. const express = require('express'); const app = express(); const htt ...

Javascript use of overlaying dynamically generated Canvases

Currently, I am developing a game to enhance my skills in HTML5 and Javascript. In the beginning, I had static canvases in the HTML body but found it difficult to manage passing them around to different objects. It is much easier for me now to allow each ...