Interactive and Online DataViz - Cheat Sheet

Complete Table of Contents

HTML

Link Description
W3 HTML Page Good basic page with simple tutorials and references
the W3 HTML Reference section Refernce on all HTML
The Mozilla MDN page More detailed reference if you want to go deeper
HTML Elements

<Element Name> Text or another element </Element Name>

EG - 

<div>This is a paragraph of text</div>
	
HTML example elements

<div></div>

<p></p>

<span></span>

<img src="">


Divs inside divs

<div>

	<div></div>

</div>

	

Styling

Styling Attribute

<div style='color: black; font-family: sans-serif;'></div>
	

CSS

Link Description
W3 CSS Page Good basic page with simple tutorials and references
the W3 CSS Reference section Refernce on all HTML
The Mozilla MDN CSS page More detailed reference if you want to go deeper
Making CSS

<head>

	<style type="text/css">

		CSS goes in here!

	</style>


	<!-- Alternatively, can keep CSS in separate file -->

	<link rel="stylesheet" type="text/css" href="./my_css_file.css">

</head>
	
Selecting multiple elements with CSS

/* All Divs */
div {
	color: red;
}

	
Selecting elements by id and class

/* Element with id 'fabulous_paragraph' */
#fabulous_paragraph {
	color: blue;
}

/* ALL Elements with class 'serious_paragraph' */
.serious_paragraph {
	color: purple;
}
	
Advanced CSS Selectors

/* All elements */
* {
	margin: 0px;
}

/* All elements with both serious and fabulous class */
.serious_paragraph.fabulous_paragraph {
	color: yellow;
}

/* All elements with either serious OR fabulous class */
.serious,.fabulous {
	color: black;
}

/* All fabulous elements inside serious elements*/
.serious .fabulous { /*Yes ... that space does something*/
	color: blue;
}

/* Only fabulous elements directly inside serious elements */
.serious > .fabulous {
	color: cyan;
}
/* This wouldn't apply to a fabulous element inside another element,
that is itself inside a serious element.  
".serious .fabulous" would apply to that however.*/
	
Giving elements ids and classes

<div id='fabulous_paragraph'>
	A paragraph of text
</div>

<div class='serious_paragraph'>
	A paragraph of text
</div>

<!--  Multiple classes -->
<div class='serious_paragraph fabulous_paragraph'>
	A paragraph of text
</div>
	
Styling with CSS

div {
	font-family: sans-serif;
	color: purple;
	background-color: yellow;

	border: 1px solid green;
}
	
Layout with CSS

div {
	width: 300; /* Width in pixels */
	height: 50%; /* Height as percentage of parent element */

	margin: 30; /* Margin in pixels */
	margin-top: 100; /* Margin on the top */
}

/* Centered horizontally */
div {
	width: 300;
	margin: auto;
}
	
FlexBox with CSS


Link Description
Guide to FlexBox Good page. Works as both cheat sheet and tutorial.
MDN Guide to FlexBox Detailed tutorial
Flexbox Froggy Interactive game tutorial

/* This div will be the container of other items */
/* It is the items inside that will be arranged according to these style rules  */

div {
	/* Makes the container a 'FlexBox' */
	display: flex;

	/* Direction items will be arranged in */
	flex-direction: column; 
	(row)

	/* How items will be arranged along the direction specified above */
	justify-content: center;  /* Ie, as direction='column', centered vertically */
	(flex-end, flex-start, space-around, space-between)

	/* How items will be arranged in opposite direction */
	align-items: center;  /* ie, as direction='column', centered horizontally */
	(flex-end, flex-start)
}
	

Javascript Fundamentals

Link Description
W3 Javascript Page All you will really need
Stackoverflow Your question or problem has happened before.
And the solution is probably here somewhere
The Mozilla MDN Javascript page More detailed reference and tutorials if you want to go deeper
Hello World - Printing to The Console

console.log('Hello World');
	
Basic Variables

// String (ie, characters)

var my_greeting = 'hello world';


// Number

var my_age = 21;
	
Making a Function


function my_function (my_argument) {
	
	console.log(my_argument);
}

	
Using a Function


my_function('Hello World');

	
Otherwise referred to as 'calling' a function

Interaction Fundamentals - Useful Javascript

Link Description
Plotly.js Home Page Downloads and documentation and examples are all here
Core D3 Documentation The reference for all the D3 interactivity we're using.
A little technical.
Lodash Useful library of lots of helpful (and fast) functions
Loading Plotly Library
 
<head>
   <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>

<!-- If you've downloaded the library -->
<head>
   <script src="plotly-latest.min.js"></script>
</head>

	
Place the script tag above in your head element.

Note that you can download the library, and refer to the local file as above.
Make sure to upload the library file to wherever your webpage will be hosted.
Inserting an Image
 
<img id='my_cat' style='width: 300px;' src="cat.jpg">
	
Img elements insert pictures/images. Place inside the body of you HTML document.
Make sure the file for the picture is in the same directory as you HTML document.
Making HTML element a javascript variable

// Make d3 separate variable for convenience 
var d3 = Plotly.d3;
var cat_img = d3.select('#my_cat'); // use '#[id of element]'

// cat_img is now the html element, but in javascript land
console.log(cat_img);
	
Adding an Event Listener

// With anonymous (ie un-named) functoin		
cat_img.on('click', function(){
	console.log('Meow!!');
})

// With named function
function cat_click(){
	console.log('Meow!!');
}
cat_imt.on('click', cat_click);
	
Getting element style in javascript land

// Get current value of width
var current_width = cat_img.style('width');

// Change width
cat_img.style('width', 700);

	
Changing elements further

var my_element = d3.select('#my_element');

// Change style //
my_element.style('color', 'red');

// Change attribute of element
my_element.attr('id', 'new_id');
my_element.attr('src', 'http://new_link.com')

// Change text of element
my_element.text('This is the new text inside the element')
	

Container Variables - for storing data

Array - ordered list of elements

var my_array = [1, 3, 6, 9];

// To get the first element of the array
console.log(my_array[0]) // counting starts from zero!

// To add an element or value to the end
my_array.push(12);

	
Object - named elements

var my_cat_object = {age: 5, weight: 3.2, name: 'fluffy'};

// to get the weight
console.log(my_cat_object.weight);

//to add another attribute
my_cat_object.happiness = 0.6;
	
Nesting containers in containers

var cat1 = {
	name: 'fluffly',
	age: 8,
	weight: 6.3,
	happiness: 0.1
};

var cat2 = {
	name: 'furball',
	age: 2,
	weight: 2.8,
	happiness: 0.9
};

// Two Objects within an array
var my_cats = [cat1, cat2];

console.log(my_cats);	
	

Mapping and Filtering

Mapping

var my_old_array = [1, 2, 3];

// Generates an exact copy
var my_new_array = my_old_array.map(function(element_in_array){
		return element_in_array;
	})
// returns [1, 2, 3]

// Generates array of values multiplied by 100
var my_bigger_array = my_old_array.map(function(element_in_array){
		return element_in_array * 100;
	})
// returns [100, 200, 300]
	
Filtering

var my_old_array = [1, 2, 3];


// Generates a copy that only has the values less than 3
var my_small_array = my_old_array.filter(function(element_in_array){
		return element_in_array < 3;
	})
// returns [1, 2]
	
Using Map and Filter to Manipulate Data

var cat1 = {
	name: 'fluffly',
	age: 8,
	weight: 6.3,
	happiness: 0.1
};

var cat2 = {
	name: 'furball',
	age: 2,
	weight: 2.8,
	happiness: 0.9
};

var cat3 = {
	name: 'satan',
	age: 10,
	weight: 10,
	happiness: 1
};

var my_cats = [cat1, cat2, cat3];

// Get names of the cats
my_cats.map(function(cat){
		return cat.name;
	})
// returns ['fluffy', 'furball', 'satan']

// Get only cats whose weight is less than 10
my_cats.map(function(cat){
		return cat.weight < 10;
	})
// returns [{name: 'fluffy', ...}, {name: 'furball', ...}]
	

Plotly Fundamentals

Link Description
Other Plotly Libraries Plotly can be used in Python/R/Matlab too.
Online Graph Maker Plotly's online plot maker. Very quick and useful.
Can generate code for you and cloud-store, making sharing plots easy.
Help for Online Graph Maker Shows the various online and cloud services Plotly provide. All free with paid premium upgrade option
Define Location of the Plot

<div id='plot_1' class='plots'></div>
		
All the graphics that Plotly creates will go within this div.
Plotly will obey what ever size you give to this div also.
Make plot location a Javascript Variable

// // Using D3 // //

var plot_1 = d3.select('#plot_1').node(); 
// node() strips away all the stuff D3 adds to the selected element, 
// which let's Plotly add it's own stuff


// // Using standard javascript // //

var plot_1 = document.getElementById('plot_1')
// no need for "#" before id
// returns only the HTML element, without any stuff added
		
Make a Trace

var trace1 = {
	x: x_vals, // data along the x axis
	y: y_vals // data along the y axis
}

		
Traces are objects that represent single pieces of data.
A single plot can have multiple traces
Make a new plot

Plotly.newPlot(plot_1, [trace1])

// Multiple traces
Plotly.newPlot(plot_1, [trace1, trace2, trace3])
		
"plot_1" = place in page to put plot (see above)

"[trace1]" = Set of pre-defined data sets. Here only one such trace, "trace1".
Even if only one trace, it must be in an array.

Plotly Customisation

Style a trace

Link Description
Full Parameter Reference Reference for all styling and layout options


var trace1 = {
	x: x_vals,
	y: y_vals,

	// Appears in tooltip and legend
	name: 'My first trace', 

	// for standard scatter plots, 
	// changes whether lines or markers or both are Used
	mode: 'lines+markers', 

	// Styling of the markers or symbols
	marker: {
		color: 'red',
		symbol: 'hexagon-open',
		size: 12,

		// Styling of the boundary lines around markers
		line: {
			color: 'blue',
			width: 2
		}
	},

	// styling of the line plot
	line: {
		color: 'black',
		shape: 'spline',
		width: 4,
		dash: '5 2'
	}

}
	
Different kinds of traces and plots

Link Description
Full Parameter Reference Reference for all styling and layout options
Plotly Examples Plenty of examples of the different plot types (and styles).



// Bar Plot
var bar_plot_trace = {
	x: x_vals,
	y: y_vals,

	type: 'bar'
}

// Histogram
var hist_trace = {
	x: x_vals,

	type: 'histogram'
}

// Box Plot

var box_plot_trace = {
	x: x_vals,

	type: 'box'
}

// HeatMap

var heat_trace = {
	z: z_vals, 
	// z_vals has to be 2d data,
	// like [[1,2],[2,1]]

	type: 'heatmap'
}
	
Customising the style and layout of the whole Plot

Link Description
Full Parameter Reference Reference for all styling and layout options
Layout Examples Examples of using various layout options.


// Make layout variable

var layout = {
	title: 'My Awesome Plot',
	showlegend: true	
}

// provide layout to Plotly function

Plotly.newPlot(plot_1, [trace1], layout)
	
Examples of Layout Options

var layout = {
	title: 'My Awesome Plot',
	showlegend: true,

	xaxis: {
		title: 'My X axis title',
		range: [-25, 75],
		autorange: 'reversed'
	},

	yaxis: {
		range: [1000, 1], // range makes axis reversed
		tickvals: [1000, 500, 100, 50, 10],
		ticktext: ['Big', 'less big', 'average', 'small', 'really small'],
		showgrid: true,
		gridwidth: 1,
		gridcolor: 'white'
	}

	paper_bgcolor: 'black',
	plot_bgcolor: 'grey'	
}
	

Plotly Interaction

Link Description
Full Function Reference List and documentation for all plot modifying functions
Animation Documentation Documentation for the animation function (see below for more details)
Interactive Fundamentals Fundamentals above may also be useful.
Update Whole Plot

// Completely new Plot //

Plotly.newPlot(myPlot, [trace1, trace2], layout);
// Quick and easy way to change a plot
	
Alter Traces

// Add trace to plot //

Plotly.addTraces(myPlot, [new_trace1, new_trace2])


// Remove Trace from Plot //

Plotly.deleteTraces(myPlot, 0); 
// 0 is the index of the trace to be removed
// IE - the first trace added is removed

// Multiple traces can be removed
Plotly.deleteTraces(myPlot, [0, 1, 2]);
	
Restyle Traces

// Make all trace markers red //

var trace_update = {
	opacity: 0.3,
	marker: {
		color: 'red'
	}}

Plotly.restyle(myPlot, trace_upate)


// Make only the third and fourth trace markers red //

Plotly.restyle(myPlot, trace_upate, [2, 3])
	
The new trace parameters are inserted into the pre-existing traces. There's no need to create whole new trace objects.
Restyle whole plot

var new_layout = {
	title: 'new Title',
	xaxis: {
		range: [0, 200]
	}
}

Plotly.relayout(myPlot, new_layout)

	
The new layout parameters are inserted into the pre-existing traces. There's no need to create whole new layout objects.
Animate a change to the plot


See the Plotly.js animation page here

var new_trace = {
	x: new_x_vals,
	y: new_y_vals,
	marker: {
		color: 'red'
	}
}

Plotly.animate(
	myPlot, 
	{
		data: [new_trace]
	}

)


// Animate Layout Change //

var zoomed_layout = {
	xaxis: {range: [0, 0.5]},
	yaxis: {range: [0, 0.5]}
}

Plotly.animate(
	myPlot,
	{
		layout: zoomed_layout
	}
)


// Control timing of animation //

Plotly.animate(
	myPlot, 
	{
		data: [new_trace]
	},
	{
		transition: {
			duration: 3000
		},
		// Frame will pause for 1 second after transition
		frame: {
			duration: 4000
		}
	}

)
	
The new trace and layout parameters are inserted into the pre-existing traces. There's no need to create whole new objects.

Plotly Interaction Events

Listening to Interaction events on the Plot

Plotly.newPlot(myPlot, [trace1])

myPlot.on('plotly_click', function(event_data){
	console.log(event_data)
})

// Also ... //

myPlot.on('plotly_hover', function(event_data){
	console.log(event_data)
})


// Typical event_data
{
  points: [{
    // index in data of the trace associated with the selected point
    curveNumber: 1,  

    // index of the selected point
    pointNumber: 1,  

    x: 1,        // x value
    y: 1,      // y value

    // ref to the trace as sent to Plotly.plot associated with the selected point
    data: {/* */},       

    // ref to the trace including all of the default attributes
    fullData: {/* */},   

    // ref to x-axis object 
    // (i.e layout.xaxis) associated with the selected point
    xaxis: {/* */},  

    // ref to y-axis object 
    yaxis: {/* */}    
  }, 
  {
    // similarly for any other selected points //
  }]
}

	
Note that the event_data provided by the event listener is a reference, which means that it is the same as the objects that define the plot. Change the event_data and you will change the plot.

Therefore, if you wish to use and modify the event_data, you may need to copy it ... see below.
Copying variables in Javascript

// Use the useful Lodash library
// go to https://lodash.com for downloads and links

<head>
	<script src="lodash.js"></script>
</head>

...

myPlot.on('plotly_click', function(event_data){
	console.log(event_data)

	// "_" = the Lodash library
	// _.cloneDeep() completely copies the object you give it
	var copy_event_data = _.cloneDeep(event_data);

})



// Make a simple copy function using JSON and built in functions

function my_copy(my_variable){

	// Converting to JSON (stringify) effectively copies the raw data
	// Converting back from JSON (parse) makes it a javascript variable

	return JSON.parse(JSON.stringify(my_variable));
}


myPlot.on('plotly_click', function(event_data){
	console.log(event_data)

	var copy_event_data = my_copy(event_data);

})

	

Loading Data Files

Loading CSV (spreadsheet-like) Files

// Eg CSV file

date,close
24-Apr-07,93.24
25-Apr-07,95.35
26-Apr-07,98.84
27-Apr-07,99.92
30-Apr-07,99.80
1-May-07,99.47

d3.csv('data.csv', function(data){
	
	// ALL CODE THAT DEALS WITH DATA GOES
	// IN THIS FUNCTION

	// CSV files become arrays
	// Each row is an element, and are javascript objects
	// Each cell in a row becomes an attribute,
	// depending on the column name


	var trace = {

		// Get all the first column values
		x: data.map(function(row){
				return row.date; // "date" is first column name
			}),

		// All second column values
		y: data.map(function(row){
				return row.close; // "close" is second column name
			})

	}

	// Will plot first column against second column
	Plotly.newPlot(myPlot, [trace])

})
	
Loading JSON (javascript-like) Files

// Eg JSON file


// array of objects, each with time-series data
[
  {
    "name": "Angola",
    "region": "Sub-Saharan Africa",
    "years": [
      1950,
      ...
    ],
    "income": [
      3363.02,
      ...
    ],
    "population": [
      4117617,
      ...
    ],
    "lifeExpectancy": [
      29.22,
      ...
    ]
  },
  {
    "name": "Benin",
    "region": "Sub-Saharan Africa",
    "years": [
      1950,
      ...
    ],
    "income": [
      1104.47,
      ...
    ],
    "population": [
      1672661,
      ...
    ],
    "lifeExpectancy": [
      36.53,
      ...
    ]
  },

  ...
]


// Loading

d3.json('data.JSON', function(data){


	// ALL CODE THAT DEALS WITH DATA GOES
	// IN THIS FUNCTION


	// JSON files simply become the variables
	// in the file itself.
	// JSON format is basically javascript variables
	// in a file.

	var trace = {
		x: data.map(function(element){
			return element.income[0];
		}),

		y: data.map(function(element){
			return element.lifeExpectancy[0];
		})
	}

	Plotly.newPlot(myPlot, [trace])
	
})
	

Hosting Your Page on Github

Putting your webpage onto GitHub Pages
Link to gif animation