Skip to content

Instantly share code, notes, and snippets.

@john-guerra
Last active August 11, 2018 01:10
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 john-guerra/340b0df640c87c8341f6648efe3f276d to your computer and use it in GitHub Desktop.
Save john-guerra/340b0df640c87c8341f6648efe3f276d to your computer and use it in GitHub Desktop.
Barchart d3v4
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
</style>
</head>
<body>
<h1>Barchart D3v4</h1>
<svg width=400
height=200
id="viz">
</svg>
<div>Paren bolas carajo! 💌</div>
<script>
let svg = d3.select("#viz"),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
g.append("g")
.attr("class", "x axis");
g.append("g")
.attr("class", "y axis");
let myData = [
{name:"John", age:23, height:1.93},
{name:"Mafe", age:22, height:1.70},
{name:"Sonia", age:27, height:1.60},
{name:"Vicente", age:73, height:0.32}
];
let x = d3.scaleBand()
.padding(0.2)
.range([0, width]);
let y = d3.scaleLinear()
.range([height, 0]);
function update(myData) {
x.domain(myData.map(d => d.name));
y.domain([0, d3.max(myData, d => d.height)]);
let points = g.selectAll(".point")
.data(myData); //update
pointsEnter = points
.enter()
.append("rect")
.attr("class", "point");
points.merge(pointsEnter) //Enter + Update
.attr("x", d => x(d.name))
.attr("y", d => y(d.height))
.attr("width", d => x.bandwidth())
.attr("height", d => height - y(d.height))
.style("fill", "steelblue");
points.exit()
.remove();
g.select(".x.axis")
.call(d3.axisBottom(x))
.attr("transform",
"translate(0, " + height + ")");
g.select(".y.axis")
.call(d3.axisLeft(y));
}
update(myData);
console.log("w", width, " h", height);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment