xarzu xarzu - 1 month ago 17
Javascript Question

How to filter and ommit input data for d3.js

I am new to D3.JS and, as a beginner, I am not sure how to handle a demanding program that will read a lot of data from a csv file and then make customized output based on the input. I am doing some test code in order to get the feel of the Here is the CSV file I am using:


And the following code works fine to produce a simple bar graph based on this input:

<doctype html>

<title> Test </title>
<script src="https://d3js.org/d3.v4.min.js"></script>
d3.csv("mydata.csv", function(error, data){

var canvas = d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 500)

.attr("width", function (d) { return d.age_group_id * 10} )
.attr("height", 48)
.attr("y", function (d, i){return i * 50} )
.attr("fill", "blue")

But what if I wanted to filter this data and only show out put for "location" == USA? I assume I would have to first read the data into a variable but I have yet to find documentation on how this is done. I also assume I will have to first define the display in a section and then load the data into this area.


When you do this:

d3.csv("mydata.csv", function(error, data){

All your CSV is loaded, as an array of objects, in a variable named data.

Thus, you can create a new dataset based on data:

var dataUsa = data.filter(function(d){
    return d.location === "USA";

And use this dataset in the bars: