Data Visualization in D3.js for the Venezuelan National Soccer Team

It’s often typical nowadays inside organizations, the extraction of valuable information from big amounts of pooled data inside of their servers. In the past years and even in our days, companies are relying on Excel spreadsheets to analyze the most important bits in a more readable format.

Nonetheless, it’s still hard to understand several lines of text laying inside a table of cells, it’s easier for the human eye, to understand graphic representations of data. Here is where the D3.js magic comes into action.

As its own website defines, D3.js is a JavaScript library for manipulating documents based on data, using HTML, SVG, and CSS.

In this example, I will use statistical data from the Venezuelan National Soccer Team to build a bar chart for the top scorers of all times.

1) First, we define an array of arrays, using the player name as the key and the number of goals as the value. Keep in mind that for this example we are going to use static data, but of course this can be changed in order to make it work dynamically, for example using AJAX to make a data request to our server.

```var scorers = [["Juan Arango", 22],
["Salomón Rondón", 14],
["Ruberth Morán", 14],
["Miku", 11],
["José Manuel Rey", 11],
["Daniel Arismendi", 9],
["Gabriel Urdaneta", 9],
["Juan García", 7],
["Ricardo David Páez", 7],
["Oswaldo Vizcarrondo", 7]
];
```

2) As a second step, we define the scale. Scales are functions that map from an input domain to an output range, in D3.js we can define it with this line of code:

``` ```  var scale = d3.scale.linear().domain( [0 , domain] ).range( [0,600] );
``````

Take into account that we have previously defined the domain for the scale:

```   var domain = d3.max( scorers , function(d){ return d[1]; });
```

3)  After this, we select the chart class, and take all the ‘divs’ inside. Then we attach the data to the selected element(s). We also set the width of the ‘div’ using the scale mapping function that we defined previously. Finally, we render the text inside the bar charts (the one that holds the player name and number of goals).

```
d3.select(".chart")
.selectAll("div")
.data(scorers)
.enter().append("div")
.style("width", function(d) {return scale(d[1]) + "px";})
.html(function(d) { return d[0] + ": " + d[1] + " goals"; });
```

4) Finally, we obtain the bar chart showing the top scorers of the Venezuelan National Team. This way, it’s easier to state that Juan Arango and Giancarlo Maldonado are the maximum scorers of all times with 22 goals playing for the “Vinotinto”, and in a descendent scale, we can watch the rest of the players who have earned a place in the history of Venezuelan soccer.

See the Pen GZEjxZ by Dario Carrasquel (@jeetkunecoder) on CodePen.