Skip to content

Instantly share code, notes, and snippets.

@lubegasimon
Last active September 25, 2019 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lubegasimon/150affb2b53acc48d581010f23f65761 to your computer and use it in GitHub Desktop.
Save lubegasimon/150affb2b53acc48d581010f23f65761 to your computer and use it in GitHub Desktop.
Age distribution basic bar chart
license: mit
var margin = { top: 20, left: 20, bottom: 20, right: 30 };
var width = 500 - margin.left - margin.right;
var height = 500 - margin.top - margin.bottom;
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
d3.csv("sample.csv").then(
(dataset) => {
var xScale = d3.scaleBand()
.domain(dataset.map(data => data.name))
.range([0, width])
.padding(0.03);
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, (d) => d.age)])
.range([height, 0]);
var xAxis = svg.append("g")
.attr("transform", `translate(0, ${height})`)
.call(d3.axisBottom(xScale).tickSizeOuter(0));
var yAxis = svg.append("g")
.call(d3.axisLeft(yScale).ticks(5).tickSizeOuter(0));
var bar = svg.selectAll(".bar")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bar")
.style("fill", "gray")
.attr("x", d => xScale(d.name))
.attr("y", d => yScale(d.age))
.attr("width", xScale.bandwidth())
.attr("height", d => height - yScale(d.age))
// make title dynamic
var title = svg.append("text")
.attr("transform", "translate(0, 0)")
.attr("x", 50)
.attr("y", 0)
.attr("font-size", "25px")
.attr("font-family", "sans-serif")
.style("fill", "blue")
.text("Age attribution amongst relatives ............")
// and axes labels https://www.tutorialsteacher.com/d3js/create-bar-chart-using-d3js
xAxis.append("text")
.attr("x", width - 100)
.attr("y", height - 100)
.attr("text-anchor", "end")
.attr("stroke", "black")
.text("Name")
yAxis.append("text")
.attr("x", width - 100)
.attr("y", height - 100)
.attr("text-anchor", "end")
.attr("stroke", "black")
.text("Age")
}
)
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>d3 play ground</title>
<link rel='stylesheet' href='../src/barChart/bar.css'>
<script src="https://d3js.org/d3.v5.js"></script>
</head>
<body>
<script src="bar.js"></script>
</body>
</html>
We can make this file beautiful and searchable if this error is corrected: It looks like row 3 should actually have 2 columns, instead of 3. in line 2.
name,age
simon,10
wax,15,
allan,27
alex,20
brian,25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment