Skip to content

Instantly share code, notes, and snippets.

@blehman
Last active December 26, 2015 12:08
Show Gist options
  • Save blehman/7148475 to your computer and use it in GitHub Desktop.
Save blehman/7148475 to your computer and use it in GitHub Desktop.
bar graph
{"description":"bar graph","endpoint":"","display":"svg","public":true,"require":[],"fileconfigs":{"inlet.js":{"default":true,"vim":false,"emacs":false,"fontSize":12},"style.css":{"default":true,"vim":false,"emacs":false,"fontSize":12},"_.md":{"default":true,"vim":false,"emacs":false,"fontSize":12},"config.json":{"default":true,"vim":false,"emacs":false,"fontSize":12}},"fullscreen":false,"play":false,"loop":false,"restart":false,"autoinit":true,"pause":true,"loop_type":"pingpong","bv":false,"nclones":15,"clone_opacity":0.4,"duration":3000,"ease":"linear","dt":0.01,"thumbnail":"http://i.imgur.com/QqnMsaf.png","ajax-caching":true}
var d = [
{name: "Alice",value: 7},
{name: "Bob", value: 20},
{name: "Carol",value: 33},
{name: "Dave", value: 9 },
{name: "Erica",value: 1 },
{name: "Frank",value: 44},
{name: "Gwen", value: 15},
{name: "Henry",value: 34},
{name: "Josh", value: 64},
{name: "Skippy",value: 133},
{name: "Jason", value: 16 },
{name: "Brian",value: 122 },
{name: "Elaine",value: 38},
{name: "Jeff", value: 8},
{name: "Mark",value: 58}
];
var height = 300,
width = 607,
margin = { left: 40, right: 0, top: 20, bottom: 45},
svg = d3.select("svg"),
container, yScale, xScale, yAxis, xAxis, bars;
container = svg.append("g").attr("transform","translate(" + [margin.left, margin.top] + ")");
yScale = d3.scale.linear()
.domain([0,d3.max(d,function(d,i) { return d.value;})])
.range([height, 0]);
names = d.map(function(d) { return d.name } )
xScale = d3.scale.ordinal()
.domain(d.map(function(d) { return d.name } ))
//.domain(d3.range(names.length) )
.rangeRoundBands([0,width], 0.25);
d3colors=d3.scale.category20();
xAxis = d3.svg.axis().scale(xScale).orient("bottom");
yAxis = d3.svg.axis().scale(yScale).orient("left");
container.append("g").attr("class","x axis")
.attr("transform","translate(" + [0, height] + ")")
.call(xAxis);
container.append("g").attr("class","y axis")
.call(yAxis);
bars = container.selectAll(".bars")
.data(d);
bars.enter()
.append("g")
.append("rect")
.classed("bars",true)
.attr({
x: function(d,i) { return xScale(i);},
y: function(d,i) { return yScale(d.value);},
width: xScale.rangeBand(),
height: function(d,i) { return height - yScale(d.value);}
})
.style("fill",function(d,i){
return d3colors(i)});
bars.append("text")
.style("text-anchor", "middle")
.attr("transform", function(d,i) { return "translate(" + [xScale(i) + (xScale.rangeBand() / 2), yScale(d.value) - 2] + ")"})
.text(function(d,i) { return d.value; });
body {
font: 13px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
rect {
shape-rendering: crispEdges;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment