How would I import a single column CSV file into a pie chart using Javascript D3?

Viewed 324

Hopefully I can explain myself properly, as I am new to JS, but I need to import a CSV file as the data for a pie chart. My csv file is just a single column, with the header "Type", and the values are not all the same. There's three types: Mediumn, Low, High and theres 63 values in total.

What I'm doing currently is d3.csv("types.csv"). After this step, I don't know how to get it to read the data as 3 seperate values. So, how would I go about doing this? Can I get it to iterate over the object array and increment an empty array and get the pie chart to use that as the data? Pseudo code example: var types = {} foreach type +1 types to end up with var types = {Low: 2, Medium: 4, High: 10} and then parse that into the pie chart.

Hope I make sense! :)

Thank you.

1 Answers

You can use d3.rollup, which reduces groups into a value, and returns an ES6 Map.

d3.rollup(data, v => v.length, d => d.type)
//              reducer       grouper

d3.rollup will reduce any group with the specified reducer: the groups are determined by the grouper function.

We group with d => d.type, so any values that have the same type are in the same group. After grouping, you'd have an Map that looks like this:

d3.group(data, d => d.type) 
== 
Map(3) {
  "High" => Array(1) // of objects
  "Medium" => Array(2)
  "Low" => Array(4)
}

Afterwards, we reduce each group, here with v => v.length. d3 takes each group (each Map) we have just created and applies that function, converting the array to a value. Here it will take the length of each group: for the Low group, it'll return 4 since there are four entries in the group.

const data = d3.csvParse(`type,value
Medium,7,2
Medium,5
Low,0.2
Low,3.4
High,2
Low,1
Low,1`)

const grouped =
  d3.rollup(data, v => v.length, d => d.type)
  
console.log("Low:",    grouped.get("Low"))
console.log("Medium:", grouped.get("Medium"))
console.log("High:",   grouped.get("High"))
<script src="https://d3js.org/d3.v6.min.js"></script>

Related