Skip to content

Instantly share code, notes, and snippets.

@UmeshMaharshi30
Forked from d3noob/.block
Last active March 8, 2020 06:26
Show Gist options
  • Save UmeshMaharshi30/319e092a2144e18cf3da1663d16834d8 to your computer and use it in GitHub Desktop.
Save UmeshMaharshi30/319e092a2144e18cf3da1663d16834d8 to your computer and use it in GitHub Desktop.
Simple discontinuous horizontal bar graph in v4
license: mit

Use the x scale to locate the starting x coordinate and y scale for determing the y coordinate. Width is given by the x(d.end)-x(d.start) Height is given by the y.bandwidth()

<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */
.bar { fill: steelblue; }
</style>
<body>
<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// set the ranges
var x = d3.scaleLinear()
.range([0, width]);
var y = d3.scaleBand()
.range([0, height])
.padding(0.1);
// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
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 + ")");
data = [
{"name" : "Bob", "start" : 0, "end" : 5},
{"name" : "Robin", "start" : 6, "end" : 7},
{"name" : "Anne", "start" : 7, "end" : 9},
{"name" : "Mark", "start" : 9, "end" : 14}
];
x.domain([0, d3.max(data, function(d) { return d.end; })]);
y.domain(data.map(function(d) { return d.name; }));
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.start); })
.attr("width", function(d) {
return x(d.end) - x(d.start) })
.attr("y", function(d, i) {
return y(d.name); })
.attr("height", function(d) { return y.bandwidth(); });
svg.append("g")
.call(d3.axisTop(x));
svg.append("g")
.call(d3.axisLeft(y));
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment