> Build visualizations in the reader’s device.
\ Otho Mantegazza _ Dataviz for Scientists _ Part 5.1
This is not a comprehensive introduction to data visualization in javascript, it’s just for breaking the ice.
JavaScript (JS) Was developed as a programming language to run directly in the browser.
Today javascript can run both in the browser (client side or front end), or independently from the browser, such as R (server side or back end).
Javascript is what makes things happen on web pages, and in many apps. It is a very widely used programming language.
You can try JS by opening the browser console.
But most of the time it is easier to try it in dedicated tools, such as:
Otherwise you can also install JS locally with node.js.
In JS you can run all fundamental arithmetic operations.
The plus sign can also be used to concatenate strings.
let arr = [1, 2, "hi!"]
for (index in arr) {
console.log("value", arr[index], "detected at postion", index)
}
The most used data structures are arrays and objects.
Javascript objects can contain arrays and vice versa:
Through HTML and CSS, the browser is one of the most sophisticated graphical tools available.
With JS, you can program in the browser, meaning that you can load data, and map the data to graphical elements in the browser.
Put the two pieces together, and you have an incredible tool for data visualization.
For example you can make a bar chart out of a table:
Open this JS Fiddle that makes a bar chart out of an excel table, about the population of Italian cities.
Although it might be fun sometimes, there’s no need to hack HTML elements to make data visualization on the web.
You can use two building blocks: SVG and D3.
Javascript, as a programming language, is not dedicated to data analysis.
Indeed when Maya Gans, Toby Hodges, and Greg Wilson wrote their book “Javascript for Data Science”, they were suggested to change the title to “Javascript versus Data Science”.
D3 is a javascript library that partially fills this gap.
It was developed by Mike Bostock, and it provides fundamental functions to transform data into web based visualizations, with SVG or Canvas.
SVG is a vector graphics specification language that allows you to declare the position, shape and style of geometrical elements in space.
All SVG is human readable, so a circle is defined by the tag “<circle>”, a rectangle by “<rect>”, and a line by “<path>”.
You can use D3 to build SVG visualization on the web.
Let’s go together through a basic quarto website that builds a visualization in the front end with D3 and SVG, starting from the penguins dataset.
Download and run the website locally as you did on the exercise on Quarto fro, the silde deck 4.1.
Run the quarto-d3-example locally: