Skip to content

Instantly share code, notes, and snippets.

@gelicia
Created October 12, 2013 14:52
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/6950800 to your computer and use it in GitHub Desktop.
Save gelicia/6950800 to your computer and use it in GitHub Desktop.
let's make a bar chart example
{"description":"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"}
//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 chart = d3.select("svg")
.attr("class", "chart")
.attr("width", 440)
.attr("height", 140)
.style("margin-left", "32px") // Tweak alignment…
.append("g")
.attr("transform", "translate(10,15)");
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range(["0px", "420px"]);
var y = d3.scale.ordinal()
.domain(data)
.rangeBands([0, 120]);
chart.selectAll("line")
.data(x.ticks(10))
.enter().append("line")
.attr("x1", x)
.attr("x2", x)
.attr("y1", 0)
.attr("y2", 120)
.style("stroke", "#ccc");
chart.selectAll(".rule")
.data(x.ticks(10))
.enter().append("text")
.attr("class", "rule")
.attr("x", x)
.attr("y", 0)
.attr("dy", -3)
.attr("text-anchor", "middle")
.text(String);
chart.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("y", y)
.attr("width", x)
.attr("height", y.rangeBand());
chart.selectAll(".bar")
.data(data)
.enter().append("text")
.attr("class", "bar")
.attr("x", x)
.attr("y", function(d) { return y(d) + y.rangeBand() / 2; })
.attr("dx", -3)
.attr("dy", ".35em")
.attr("text-anchor", "end")
.text(String);
chart.append("line")
.attr("y1", 0)
.attr("y2", 120)
.style("stroke", "#000");
.chart {
margin-left: 42px;
font: 10px sans-serif;
shape-rendering: crispEdges;
}
.chart div {
background-color: steelblue;
text-align: right;
padding: 3px;
margin: 1px;
color: white;
}
.chart rect {
stroke: white;
fill: steelblue;
}
.chart text.bar {
fill: white;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment