>Data Visualization in Javascript

> 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

JavaScript (JS) Was developed as a programming language to run directly in the browser.

  • It was released in 1995 by Brendan Eich,
  • Javascript latest version is ECMAScript 6, abbreviated as ES6.
  • Besides the name, it has nothing to do with Java.

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

Javascript is what makes things happen on web pages, and in many apps. It is a very widely used programming language.

Try JS

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.

Assignments

You can define variable with: var, let or const; and assign values to them with =. var can be reassigned, let and const are constants and cannot be reassigned.

var a = "some text"
let b = "more text"
const c = "something else"

Check what’s stored in a variable with console.log().

console.log(a)

Basic operations

In JS you can run all fundamental arithmetic operations.

The plus sign can also be used to concatenate strings.

"Hello" + " " + "world" + "!"

Control Flow

Loops

let arr = [1, 2, "hi!"]
for (index in arr) {
  console.log("value", arr[index], "detected at postion", index)
}


If Else

let a = 3
if (a === 3) {
  console.log('a is equal to', a)
} else {
  console.log('nope')
}

Data structures

The most used data structures are arrays and objects.

Arrays

Arrays are series of values between square brackets […].

let arr = [1, 2, "hi!"]
let arr2 = [
  1,
  [1, 3, "r", 1],
  arr
  ]

An array can contain any data type, and it is ordered. Any item can be accessed by index and can be iterated upon.

Objects

Objects are collections of key-value pairs.

let cities = {
    "Rome": {
    "pop": 2.761,
  },
  "Milan": {
    "pop": 1.352,
  },
  "Naples": {
    "pop": 0.914,
  },
}

They can contain any data type. Any item can be accessed by key, and they can be iterated upon.

Objects and Arrays

Javascript objects can contain arrays and vice versa:

const pop = [
  {
    "town": "Rome",
    "pop": 2.761,
  },
  {
    "town": "Milan",
    "pop": 1.352,
  },
  {
    "town": "Naples",
    "pop": 0.914,
  },
]

JSON

The combination of objects and array notation is known as JSON, or JavaScript Object Notation.

[
  {
    "town": "Rome",
    "pop": 2.761,
  },
  {
    "town": "Milan",
    "pop": 1.352,
  },
  {
    "town": "Naples",
    "pop": 0.914,
  },
]

JSON files store data in plain text, such as CSV.

Dataviz in the browser.

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.

Dataviz in the browser.

For example you can make a bar chart out of a table:

Exercise

Open this JS Fiddle that makes a bar chart out of an excel table, about the population of Italian cities.

  • Change the color of the bars.
  • Add curved round corners to the bars.
  • Add a new bar with the fourth highest populated city.
  • Arrange the bars from smaller to the bigger.
  • Color yellow only the bar that shows data about Milan.
  • [OPTIONAL] Make a vertical bar chart.

Some Resources About JS

No Need To Hack HTML

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.

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

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 Try Them

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.

  1. You can find the source code from Github at: https://github.com/othomantegazza/quarto-d3-example.
  2. And the website already deployed at https://quarto-d3-example.otho.app/.

Download and run the website locally as you did on the exercise on Quarto fro, the silde deck 4.1.

Exercise

Run the quarto-d3-example locally:

  1. Familiarize yourself with the javascript code in js/scatterplot.js.
  • Remove and change pieces, see what happens.
  • Use the function console.log() to print the variables at the javascript console, and understand what’s in there.
  1. Color the circles.
  2. Color the border of the circle, leave the center empty.

Exercise

  1. Transform the axes to log scale.
  2. Change the variables represented in the x or y axes.
  3. EXTRA: Map the species of the penguins to the color of the circles.