Skip to content

Instantly share code, notes, and snippets.

@HarryStevens
Last active September 13, 2019 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save HarryStevens/522992df55dc6bd8d7eca3f9e9c75de4 to your computer and use it in GitHub Desktop.
Save HarryStevens/522992df55dc6bd8d7eca3f9e9c75de4 to your computer and use it in GitHub Desktop.
Bar Chart with "Popout"
license: gpl-3.0

Use d3.scaleBand() to create a bar chart, then apply styles to a category of bars to provide visual "popout." See pp.39-40 of this slideshow for a brief discussion of visual popout.

name value category
Andrew 95.77 A
Matthew 103.62 A
Mark 94.2 A
Luke 91.06 A
John 76.93 A
Jimmy 65.94 B
Bill 64.37 A
Bob 54.95 A
Kate 74.93 A
Alice 35.13 A
Sally 85.74 B
Mary 25.83 B
Jenny 23.65 A
Barbara 13.05 A
<html>
<head>
<style>
body {
font-family: "Helvetica Neue", sans-serif;
width: 607.141px;
margin: 0 auto;
display: table;
}
</style>
</head>
<body>
<div class="chart"></div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="scripts.js"></script>
</body>
</html>
var margin = {top: 0, right: 150, bottom: 0, left: 0},
width = 607.141 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var svg = d3.select(".chart").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 + ")");
var x = d3.scaleLinear()
.range([0,width]);
var y = d3.scaleBand()
.rangeRound([height,0])
.padding(0.2)
d3.csv("data.csv",types,function(error,data){
if (error) throw error;
data.sort(function(a,b){
return a.value-b.value;
});
x.domain([0,d3.max(data, function(d){ return d.value; })]);
y.domain(data.map(function(d) { return d.name; }));
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", 0)
.attr("y", function(d){ return y(d.name); })
.attr("width", function(d){ return x(d.value); })
.attr("height", y.bandwidth())
.style("fill", function(d){ d.category === 'A' ? fill = "#CCC" : fill = "#B44682"; return fill; });
svg.selectAll(".bar-label")
.data(data)
.enter().append("text")
.attr("class", "bar-label")
.attr("x", function(d){ return x(d.value) + 3; })
.attr("y", function(d){ return y(d.name); })
.attr("dy", y.bandwidth()-2)
.attr("text-anchor", "start")
.text(function(d,i){ return d.name + " (" + d.value + ")"; })
.style('font-weight', function(d){ d.category === 'A' ? fontWeight = '400' : fontWeight = '900'; return fontWeight; });
});
function types(d){
d.value = +d.value;
return d;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment