Skip to content

Instantly share code, notes, and snippets.

@cdagli
Created January 5, 2018 19:10
Show Gist options
  • Save cdagli/ab633e23a9d71583ad6bd599bdc7f95c to your computer and use it in GitHub Desktop.
Save cdagli/ab633e23a9d71583ad6bd599bdc7f95c to your computer and use it in GitHub Desktop.
fresh block
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
var data = [
{
"salesperson": "Bob",
"sales": 33
},
{
"salesperson": "Robin",
"sales": 12
},
{
"salesperson": "Anne",
"sales": 41
},
{
"salesperson": "Mark",
"sales": 16
},
{
"salesperson": "Joe",
"sales": 59
},
{
"salesperson": "Eve",
"sales": 38
},
{
"salesperson": "Karen",
"sales": 21
},
{
"salesperson": "Kirsty",
"sales": 25
},
{
"salesperson": "Chris",
"sales": 30
},
{
"salesperson": "Lisa",
"sales": 47
},
{
"salesperson": "Tom",
"sales": 5
},
{
"salesperson": "Stacy",
"sales": 20
},
{
"salesperson": "Charles",
"sales": 13
},
{
"salesperson": "Mary",
"sales": 29
}
];
var margin = {top: 20, right: 20, bottom: 50, left: 70},
width = 800 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scaleBand()
.range([0, data.length * 100])
.paddingInner(0.3);
var y = d3.scaleLinear()
.range([height, 0]);
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 + ")");
x.domain(data.map(function(d) { return d.salesperson; }));
y.domain([0, d3.max(data, function(d) { return d.sales; })]);
var barsGroup = svg.append('g');
//Set the clipping path to the group (g element) that you want to clip
barsGroup.attr('clip-path','url(#my-clip-path)');
// append the rectangles for the bar chart
var bars = barsGroup.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.salesperson); })
.attr("width", x.bandwidth())
.attr("y", function(d) { return y(d.sales); })
.attr("height", function(d) { return height - y(d.sales); })
.style("fill", "steelblue");
var xAxis = svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x)).selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", ".2em")
.attr("transform", "rotate(-65)");;
var yAxis = svg.append("g")
.call(d3.axisLeft(y));
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x",0 - (height / 2))
.attr("dy", "1em")
.text("Count");
svg.append("text")
.attr("transform",
"translate(" + (width/2) + " ," + (height + margin.top + 30) + ")")
.style("text-anchor", "middle")
.text("Sales Person")
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment