Skip to content

Instantly share code, notes, and snippets.

@larsvers
Created November 14, 2019 14:41
Show Gist options
  • Save larsvers/26b97c3389011d55c7d3bd34dafb391c to your computer and use it in GitHub Desktop.
Save larsvers/26b97c3389011d55c7d3bd34dafb391c to your computer and use it in GitHub Desktop.
Bar q
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>main</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="//unpkg.com/d3"></script>
<style type="text/css">
</style>
</head>
<body>
<div id="content"></div>
<script>
d3.csv("students.csv").then(data => {
const xValue = d => (+d.students * 1000);
const yValue = d => d.faculty;
const W = 600;
const H = 200;
var svg = d3.select("#content")
.append("svg")
.attr("width", W)
.attr("height", H);
//sets margins and inner height and width
const margin = {top: 20, right: 40, bottom: 50, left: 100};
const innerWidth = W - margin.left - margin.right;
const innerHeight = H - margin.top - margin.bottom;
const xScale = d3.scaleLinear() //Domain entspricht Data space whereas Range entsprich screen space
.domain([0, d3.max(data, xValue)])
.range([0, innerWidth]);
const yScale = d3.scaleBand()
.domain(data.map(yValue))
.range([0, innerHeight])
.padding(0.1);
const g = svg.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);
g.append('g').call(d3.axisLeft(yScale));
g.append('g')
.call(d3.axisBottom(xScale))
.attr('transform', `translate(0, ${innerHeight})`);
g.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('y', d => yScale(yValue(d)))
.attr('width', d => xScale(xValue(d)))
.attr('height', yScale.bandwidth());
});
</script>
</body>
</html>
faculty students
maths 100
philosophy 300
biology 220
latin 50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment