D3 Scatterplot - Loading
by Dan Shahin
HTML
<h3>Visual Analytics Course - Oxford University</h3>
<p>Scatter plot - loading data <span class="name">Eamonn Maguire</span>
</p>
<div id="scatter-load"></div>
CSS
body {
font-family:"Helvetica Neue";
color: #686765;
}
.name {
float:right;
color:#27aae1;
}
.axis {
fill: none;
stroke: #AAA;
stroke-width: 1px;
}
text {
stroke: none;
fill: #666666;
font-size: .6em;
font-family:"Helvetica Neue"
}
.label {
fill: #414241;
}
.node {
cursor:pointer;
}
.dot {
opacity: .7;
cursor: pointer;
}
JavaScript
var chocolates = [{
"name": "Dairy Milk",
"manufacturer": "cadbury",
"price": 45,
"rating": 2
}, {
"name": "Galaxy",
"manufacturer": "Nestle",
"price": 42,
"rating": 3
}, {
"name": "Lindt",
"manufacturer": "Lindt",
"price": 80,
"rating": 4
}, {
"name": "Hershey",
"manufacturer": "Hershey",
"price": 40,
"rating": 1
}, {
"name": "Dolfin",
"manufacturer": "Lindt",
"price": 90,
"rating": 5
}, {
"name": "Bournville",
"manufacturer": "cadbury",
"price": 70,
"rating": 2
}];
// call the method below
showScatterPlot(chocolates);
function showScatterPlot(data) {
// just to have some space around items.
var margins = {
"left": 40,
"right": 30,
"top": 30,
"bottom": 30
};
var width = 500;
var height = 500;
// this will be our colour scale. An Ordinal scale.
var colors = d3.scale.category10();
// we add the SVG component to the scatter-load div
var svg = d3.select("#scatter-load").append("svg").attr("width", width).attr("height", height).append("g")
.attr("transform", "translate(" + margins.left + "," + margins.top + ")");
// this sets the scale that we're using for the X axis.
// the domain define the min and max variables to show. In this case, it's the min and max prices of items.
// this is made a compact piece of code due to d3.extent which gives back the max and min of the price variable within the dataset
var x = d3.scale.linear()
.domain(d3.extent(data, function (d) {
return d.price;
}))
// the range maps the domain to values from 0 to the width minus the left and right margins (used to space out the visualization)
.range([0, width - margins.left - margins.right]);
// this does the same as for the y axis but maps from the rating variable to the...