Skip to content

Instantly share code, notes, and snippets.

@gelicia
Created October 12, 2013 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gelicia/6950817 to your computer and use it in GitHub Desktop.
Save gelicia/6950817 to your computer and use it in GitHub Desktop.
horizontal let's make a bar chart example
{"description":"horizontal let's make a bar chart example","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/jeyc7Km.png"}
//modified skip to the end from the end of http://mbostock.github.io/d3/tutorial/bar-1.html
var data = [4, 8, 15, 16, 23, 42];
var chartProp = {maxWidth : 400, maxHeight: 420}
var chart = d3.select("svg")
.attr("class", "chart")
.attr("width", chartProp.maxWidth + 20)
.attr("height", chartProp.maxHeight + 20)
.append("g")
.attr("transform", "translate(10,15)");
var x = d3.scale.ordinal()
.domain(data)
.rangeRoundBands([0, chartProp.maxWidth], 0.1);
var y = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, chartProp.maxHeight]);
var color = d3.scale.category20();
chart.selectAll("line")
.data(y.ticks(10))
.enter().append("line")
.attr({
x1: 0,
x2: chartProp.maxWidth,
y1: function(d){ return chartProp.maxHeight - y(d);},
y2: function(d){ return chartProp.maxHeight - y(d);}
})
.style("stroke", "#ccc");
chart.selectAll(".rule")
.data(y.ticks(10))
.enter().append("text")
.attr({
"class": "rule",
y: function(d){ return chartProp.maxHeight - y(d);},
x: 0,
dy: -3,
"text-anchor": "middle"
})
.text(String);
chart.selectAll("rect")
.data(data)
.enter().append("rect")
.attr({
x: x,
y: function(d){ return chartProp.maxHeight - y(d);},
width: x.rangeBand(),
height: function(d){return y(d);},
fill : function(d,i){return color(i);}
});
chart.selectAll(".bar")
.data(data)
.enter().append("text")
.attr({
"class": "bar",
x: function(d) { return x(d) + x.rangeBand() / 2; },
y: function(d){ return chartProp.maxHeight - y(d);},
dy: -3,
"text-anchor": "middle"
})
.text(String);
chart.append("line")
.attr({
x1: 0,
x2: chartProp.maxWidth,
y1: chartProp.maxHeight,
y2: chartProp.maxHeight
})
.style("stroke", "#000");
.chart {
margin-left: 42px;
margin-top: 10px;
font: 10px sans-serif;
shape-rendering: crispEdges;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment