block by harrystevens 522992df55dc6bd8d7eca3f9e9c75de4

Bar Chart with "Popout"

Full Screen

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.

index.html

<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>

data.csv

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

scripts.js

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;
}