Repository navigation
For this project I'm using D3. D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation. d3js.org.
I'm using D3 to render circles on screen and connect them with links.
I load in D3 with <script src="https://d3js.org/d3.v5.min.js" charset="utf-8"></script>
async function getData(){
await d3.csv("../data/data.csv", entry => {
return data.push(entry)
})
await d3.csv("../data/top2017.csv", entry => {
return metaData.push(entry)
})
await d3.csv("../data/holidays.csv", entry => {
return holidays.push(entry)
})
}This function is where I load multiple csv data sources with D3. The function is asynchronous and I await every result to make sure I have all the data pushed to the correct array before continueing.
const svg = svgContainer.append("svg")
.attr("viewBox", [-400, 50, 960, 900]).attr('id', 'svg'+i)
const root = d3.hierarchy(el);
const links = root.links();
const nodes = root.descendants();
const container = svg.append("g").attr('id', meta[i].class)
const simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(links).id(d => d.id).distance((Math.sqrt(el.amountPlayed)/10) * 2).strength(1))
.force("charge", d3.forceManyBody().strength(-100))
.force('collision', d3.forceCollide().radius(function (d) {
return d.radius
}))First, I create one main svg element and I give the correct viewbox so the visualisation is displayed in the correct position on screen. After that, I tell the visualisation how to behave. The length of the links is decided, the collision prevention is calculate.
const link = container.append("g").attr("class", 'links')
.attr("stroke", "#999")
.attr("stroke-opacity", 0.6)
.selectAll("line")
.data(links)
.join("line");
const node = container.append("g").attr("class", 'nodes')
.attr("fill", "#fff")
.attr('style', 'cursor: pointer;')
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("fill", d => d.children ? null : "#1ED760")
.attr("r", d => Math.sqrt(d.data.amountPlayed) / 10)
.call(drag(simulation));Every link and circle has some attributes decided, based on whether or not it is a track or a country circle. The data is also bound to both the circles and the links.
Some attributes accept a value or variable, some attributes only accept a callback function. An example is .attr("fill", d => d.color). Before I realised I needed a callback function to give the source to the attribute, I tried plainly giving it a variable, but that did not work because it only accepts callback functions.