Skip to content

Instantly share code, notes, and snippets.

@capesean
Created Apr 9, 2014
Embed
What would you like to do?
Bar Graph for Public Data
{"description":"Bar Graph for Public Data","endpoint":"","display":"svg","public":true,"require":[],"fileconfigs":{"inlet.js":{"default":true,"vim":false,"emacs":false,"fontSize":12},"styles.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},"tip.js":{"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,"ajax-caching":true,"thumbnail":"http://i.imgur.com/SnUwHBG.gif"}
/**************************** setup - before getting data ****************************/
var width = 850,
height = 400,
paddingTop = 20,
paddingLeft = 50,
paddingRight = 20,
paddingBottom = 30,
barSpacing = 1;
var availWidth = width - (paddingLeft + paddingRight),
availHeight = height - (paddingTop + paddingBottom);
var y = d3.scale.linear()
.range([availHeight+paddingTop, paddingTop]);
var svg = d3.select("svg")
.attr("width", width)
.attr("height", height);
/**************************** fetch data ****************************/
var data = [
{"indicatorID":"2cf454b4-475c-40d4-805c-01c6d3539ffa","municipalityID":"3e4a803d-f4e2-43a3-8ce5-cd47c1ce5c1a","dateID":2011,"factValue":0.1764,"error":null,"label":"first"},
{"indicatorID":"2ea0e369-ab5d-4d56-9fbe-46cabef3f506","municipalityID":"3e4a803d-f4e2-43a3-8ce5-cd47c1ce5c1a","dateID":2011,"factValue":0.1524,"error":null,"label":"second"},
{"indicatorID":"2a0dda71-2e7e-4329-a0b9-965e0f4441c5","municipalityID":"3e4a803d-f4e2-43a3-8ce5-cd47c1ce5c1a","dateID":2011,"factValue":0.2102,"error":null,"label":"third"},
{"indicatorID":"21f4318c-9ecc-4af2-912c-e1cdc33e0ae5","municipalityID":"3e4a803d-f4e2-43a3-8ce5-cd47c1ce5c1a","dateID":2011,"factValue":0.1637,"error":null,"label":"fourth"},
{"indicatorID":"8edf01b2-4580-4b8f-affc-1fe00c9eb9d9","municipalityID":"3e4a803d-f4e2-43a3-8ce5-cd47c1ce5c1a","dateID":2011,"factValue":0.1248,"error":null,"label":"fifth"},
{"indicatorID":"b5592349190-c783-4936-b425-1981824e20d4","municipalityID":"3e4a803d-f4e2-43a3-8ce5-cd47c1ce5c1a","dateID":2011,"factValue":0.0877,"error":null,"label":"sixth"},
{"indicatorID":"c8132cbf-52c2-4376-9e1d-c337b8e6ed19","municipalityID":"3e4a803d-f4e2-43a3-8ce5-cd47c1ce5c1a","dateID":2011,"factValue":0.0495,"error":null,"label":"seventh"},
{"indicatorID":"093f61a3-658c-48ab-9b8a-719dd5e3efa0","municipalityID":"3e4a803d-f4e2-43a3-8ce5-cd47c1ce5c1a","dateID":2011,"factValue":0.0248,"error":null,"label":"eighth"},
{"indicatorID":"9318d75c-8d96-445c-9c96-7057bef4d4b9","municipalityID":"3e4a803d-f4e2-43a3-8ce5-cd47c1ce5c1a","dateID":2011,"factValue":0.0106,"error":null,"label":"ninth"}
];
y.domain([0, d3.max(data, function (d) { return d.factValue; })]);
var barWidth = availWidth / data.length;
var bar = svg.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function (d, i) { return "translate(" + ((i * barWidth) + paddingLeft + (barSpacing / 2)) + ",0)"; });
bar.append("rect")
.attr("y", function (d) { return y(d.factValue); })
.attr("height", function (d) { return availHeight - y(d.factValue) + paddingTop; })
.attr("width", barWidth - barSpacing);
bar.append("text")
.attr("x", (barWidth - barSpacing) / 2)
.attr("y", function (d) { return y(d.factValue) + 3; })
.attr("dy", ".75em")
.text(function (d) { return d3.format(".1%")(d.factValue); });
var labels = [];
data.forEach(function(d){labels.push(d.label)});
// x-axis
var xAxisScale = d3.scale.ordinal()
.domain(labels)
.rangeRoundBands([paddingLeft, paddingLeft + availWidth], 0)
var xAxis = d3.svg.axis()
.scale(xAxisScale)
.ticks(4);
svg.append("g")
.classed("axis", true)
.attr("transform", "translate(" + [0, availHeight + paddingTop] + ")")
.call(xAxis);
// y-axis
var yAxisScale = d3.scale.linear()
.domain([d3.max(data, function (d) { return d.factValue; }), 0])
.range([0, availHeight]);
var yAxis = d3.svg.axis().scale(yAxisScale).orient("left").ticks(5).tickFormat(d3.format("%"));
svg.append("g")
.classed("axis", true)
.attr("transform", "translate(" + paddingLeft + ","+paddingTop+")")
.call(yAxis)
svg rect {
fill: steelblue;
}
svg rect:hover {
fill: orange;
}
svg text {
fill: white;
stroke: none;
font: 10px sans-serif;
text-anchor: middle;
}
.axis {
font-size: 10px;
}
.axis path {
fill: none;
stroke: #000000;
}
.axis .tick line {
stroke: #000;
}
.axis .tick text {
stroke: none;
fill:black;
}
/* tips */
.d3-tip {
line-height: 1;
font-weight: bold;
padding: 12px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 2px;
}
/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
box-sizing: border-box;
display: inline;
font-size: 10px;
width: 100%;
line-height: 1;
color: rgba(0, 0, 0, 0.8);
content: "\25BC";
position: absolute;
text-align: center;
}
/* Style northward tooltips differently */
.d3-tip.n:after {
margin: -1px 0 0 0;
top: 100%;
left: 0;
}
// d3.tip
// Copyright (c) 2013 Justin Palmer
//
// Tooltips for d3.js SVG visualizations
// Public - contructs a new tooltip
//
// Returns a tip
d3.tip = function() {
var direction = d3_tip_direction,
offset = d3_tip_offset,
html = d3_tip_html,
node = initNode(),
svg = null,
point = null,
target = null
function tip(vis) {
svg = getSVGNode(vis)
point = svg.createSVGPoint()
document.body.appendChild(node)
}
// Public - show the tooltip on the screen
//
// Returns a tip
tip.show = function() {
var args = Array.prototype.slice.call(arguments)
if(args[args.length - 1] instanceof SVGElement) target = args.pop()
var content = html.apply(this, args),
poffset = offset.apply(this, args),
dir = direction.apply(this, args),
nodel = d3.select(node), i = 0,
coords
nodel.html(content)
.style({ opacity: 1, 'pointer-events': 'all' })
while(i--) nodel.classed(directions[i], false)
coords = direction_callbacks.get(dir).apply(this)
nodel.classed(dir, true).style({
top: (coords.top + poffset[0]) + 'px',
left: (coords.left + poffset[1]) + 'px'
})
return tip
}
// Public - hide the tooltip
//
// Returns a tip
tip.hide = function() {
nodel = d3.select(node)
nodel.style({ opacity: 0, 'pointer-events': 'none' })
return tip
}
// Public: Proxy attr calls to the d3 tip container. Sets or gets attribute value.
//
// n - name of the attribute
// v - value of the attribute
//
// Returns tip or attribute value
tip.attr = function(n, v) {
if (arguments.length < 2 && typeof n === 'string') {
return d3.select(node).attr(n)
} else {
var args = Array.prototype.slice.call(arguments)
d3.selection.prototype.attr.apply(d3.select(node), args)
}
return tip
}
// Public: Proxy style calls to the d3 tip container. Sets or gets a style value.
//
// n - name of the property
// v - value of the property
//
// Returns tip or style property value
tip.style = function(n, v) {
if (arguments.length < 2 && typeof n === 'string') {
return d3.select(node).style(n)
} else {
var args = Array.prototype.slice.call(arguments)
d3.selection.prototype.style.apply(d3.select(node), args)
}
return tip
}
// Public: Set or get the direction of the tooltip
//
// v - One of n(north), s(south), e(east), or w(west), nw(northwest),
// sw(southwest), ne(northeast) or se(southeast)
//
// Returns tip or direction
tip.direction = function(v) {
if (!arguments.length) return direction
direction = v == null ? v : d3.functor(v)
return tip
}
// Public: Sets or gets the offset of the tip
//
// v - Array of [x, y] offset
//
// Returns offset or
tip.offset = function(v) {
if (!arguments.length) return offset
offset = v == null ? v : d3.functor(v)
return tip
}
// Public: sets or gets the html value of the tooltip
//
// v - String value of the tip
//
// Returns html value or tip
tip.html = function(v) {
if (!arguments.length) return html
html = v == null ? v : d3.functor(v)
return tip
}
function d3_tip_direction() { return 'n' }
function d3_tip_offset() { return [0, 0] }
function d3_tip_html() { return ' ' }
var direction_callbacks = d3.map({
n: direction_n,
s: direction_s,
e: direction_e,
w: direction_w,
nw: direction_nw,
ne: direction_ne,
sw: direction_sw,
se: direction_se
}),
directions = direction_callbacks.keys()
function direction_n() {
var bbox = getScreenBBox()
return {
top: bbox.n.y - node.offsetHeight,
left: bbox.n.x - node.offsetWidth / 2
}
}
function direction_s() {
var bbox = getScreenBBox()
return {
top: bbox.s.y,
left: bbox.s.x - node.offsetWidth / 2
}
}
function direction_e() {
var bbox = getScreenBBox()
return {
top: bbox.e.y - node.offsetHeight / 2,
left: bbox.e.x
}
}
function direction_w() {
var bbox = getScreenBBox()
return {
top: bbox.w.y - node.offsetHeight / 2,
left: bbox.w.x - node.offsetWidth
}
}
function direction_nw() {
var bbox = getScreenBBox()
return {
top: bbox.nw.y - node.offsetHeight,
left: bbox.nw.x - node.offsetWidth
}
}
function direction_ne() {
var bbox = getScreenBBox()
return {
top: bbox.ne.y - node.offsetHeight,
left: bbox.ne.x
}
}
function direction_sw() {
var bbox = getScreenBBox()
return {
top: bbox.sw.y,
left: bbox.sw.x - node.offsetWidth
}
}
function direction_se() {
var bbox = getScreenBBox()
return {
top: bbox.se.y,
left: bbox.e.x
}
}
function initNode() {
var node = d3.select(document.createElement('div'))
node.style({
position: 'absolute',
opacity: 0,
pointerEvents: 'none',
boxSizing: 'border-box'
})
return node.node()
}
function getSVGNode(el) {
el = el.node()
if(el.tagName.toLowerCase() == 'svg')
return el
return el.ownerSVGElement
}
// Private - gets the screen coordinates of a shape
//
// Given a shape on the screen, will return an SVGPoint for the directions
// n(north), s(south), e(east), w(west), ne(northeast), se(southeast), nw(northwest),
// sw(southwest).
//
// +-+-+
// | |
// + +
// | |
// +-+-+
//
// Returns an Object {n, s, e, w, nw, sw, ne, se}
function getScreenBBox() {
var targetel = target || d3.event.target,
bbox = {},
matrix = targetel.getScreenCTM(),
tbbox = targetel.getBBox(),
width = tbbox.width,
height = tbbox.height,
x = tbbox.x,
y = tbbox.y,
scrollTop = document.documentElement.scrollTop || document.body.scrollTop,
scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft
point.x = x + scrollLeft
point.y = y + scrollTop
bbox.nw = point.matrixTransform(matrix)
point.x += width
bbox.ne = point.matrixTransform(matrix)
point.y += height
bbox.se = point.matrixTransform(matrix)
point.x -= width
bbox.sw = point.matrixTransform(matrix)
point.y -= height / 2
bbox.w = point.matrixTransform(matrix)
point.x += width
bbox.e = point.matrixTransform(matrix)
point.x -= width / 2
point.y -= height / 2
bbox.n = point.matrixTransform(matrix)
point.y += height
bbox.s = point.matrixTransform(matrix)
return bbox
}
return tip
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment