Home > Mobile >  How to find the sum of values?
How to find the sum of values?

Time:01-18

I am trying to create a line chart in d3.js (version 6), where the x-axis is the infections and y-axis is the date. The csv file looks like this

code,country,date,cases
AFG,Afghanistan,2020-03-23,0.059,
US,United States,2020-03-24,0.063,
FR,France,2020-03-25,0.174,
GR,Germany,2020-03-26,0.195,
AFG,Afghanistan,2020-03-23,0.233,
US,United States,2020-03-24,0.285,
FR,France,2020-03-25,0.278,
GR,Germany,2020-03-26,0.257,

Now I want to get the total value for each date (so for 2020-03-2 the value should be 0.292, etc.) I read that d3.rollups would make this work but I am not sure I am using it right. This is what I have done so far:

const parseDate= d3.timeParse("%Y-%m-%d");

d3.csv("./multilinedata.csv").then(function(dataline) {
    dataline.forEach(function(d) {
        d.date = parseDate(d.date);
        d.cases=  d.cases
    });
    const totalCase = d3.rollups(dataline, g => g.sum, d=>d.date);
    console.log(totalCase);

This is the output I get

enter image description here

Would really appreciate it if someone could help me out! Thank you!

CodePudding user response:

First of all, your CSV is incorrect, drop those commas at the end of each row.

That said, the d3.rollup method requires the data array, the reduce function itself and the keys. This is how it should be in your case:

const totalCase = d3.rollup(data, d => d3.sum(d, e => e.cases), d => d.date);

Here is the demo (because this is a Map look at your browser's console, not the SO snippet's one):

const csv = `code,country,date,cases
AFG,Afghanistan,2020-03-23,0.059
US,United States,2020-03-24,0.063
FR,France,2020-03-25,0.174
GR,Germany,2020-03-26,0.195
AFG,Afghanistan,2020-03-23,0.233
US,United States,2020-03-24,0.285
FR,France,2020-03-25,0.278
GR,Germany,2020-03-26,0.257`;

const data = d3.csvParse(csv, d3.autoType);

const totalCase = d3.rollup(data, d => d3.sum(d, e => e.cases), d => d.date);

console.log(totalCase)
<script src="https://d3js.org/d3.v6.min.js"></script>

CodePudding user response:

this is a methode of reduce can find the sum of values of array.

you can put your values in array and do this methode.

syntax:

yourArry.reduce((total, value) => total   value);

I hove your probleme was solved.

  • Related