Skip to content

Instantly share code, notes, and snippets.

@schmidsi
Last active April 30, 2017 13:43
Show Gist options
  • Save schmidsi/6647bb23fe18af32b600166cd2a39387 to your computer and use it in GitHub Desktop.
Save schmidsi/6647bb23fe18af32b600166cd2a39387 to your computer and use it in GitHub Desktop.
ivis exercise 03: intro to d3
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
margin: 15px;
background-color: #F1F3F3
}
.bar.skill {
fill: #6F257F;
}
.bar.goal {
fill: #e2d3e5;
}
.axis path,
.axis line {
fill: none;
stroke: #D4D8DA;
stroke-width: 1px;
shape-rendering: crispEdges;
}
.x path {
display: none;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
const data = [{
library: 'react',
skills: 4,
goal: 5
}, {
library: 'redux',
skills: 4,
goal: 5
}, {
library: 'd3',
skills: 2,
goal: 4
}];
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 40},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var x = d3.scaleLinear()
.range([0, width])
.domain([0, 6]);
var y = d3.scaleBand()
.range([height, 0])
.domain(data.map(datum => datum.library))
.padding(0.1);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
g.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).ticks(5).tickFormat(d => d).tickSizeInner([-height]));
g.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(y));
g.selectAll(".bar.goal")
.data(data)
.enter().append("rect")
.attr("class", "bar goal")
.attr("x", d => x(d.skills))
.attr("height", y.bandwidth())
.attr("y", function(d) { return y(d.library); })
.attr("width", d => x(d.goal - d.skills))
g.selectAll(".bar.skill")
.data(data)
.enter().append("rect")
.attr("class", "bar skill")
.attr("x", 0)
.attr("height", y.bandwidth())
.attr("y", function(d) { return y(d.library); })
.attr("width", function(d) { return x(d.skills); })
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment