Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find the sum of values?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading