Skip to content

Instantly share code, notes, and snippets.

@parryc
Created December 10, 2012 00:16
Show Gist options
  • Save parryc/4247623 to your computer and use it in GitHub Desktop.
Save parryc/4247623 to your computer and use it in GitHub Desktop.
Config chart example

A configurable d3 chart example. Based on this

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.arc path {
stroke: #fff;
}
#pie1 {
stroke: black;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var data = [{"label" : "list 1", "value":500, "color":"#0000FF"},
{"label" : "list 2", "value":300, "color":"#FF0000"},
{"label" : "list 3", "value":400, "color":"#00FF00"},
{"label" : "other", "value":200, "color":"#ABCDEF"}];
var config = {"w" : 900, "h": 500};
var chart = chart(config);
d3.select("#pie2").data(data).call(chart);
data[0].value = 100;
d3.select("#pie1").data(data).call(chart);
data[1].color = "#FBDE33";
function chart(config){
var w = config.w,
h = config.h,
r = Math.min(w, h) / 2 - 10,
loc = "#pie1";
function chart() {
var vis = this.append("svg:svg")
.data([data])
.attr("width", w)
.attr("height", h)
.append("svg:g")
.attr("transform", "translate(" + (r+5) + "," + (r+5) + ")");
var arc = d3.svg.arc()
.outerRadius(r);
var pie = d3.layout.pie()
.value(function(d) { return d.value; });
var arcs = vis.selectAll("g.slice")
.data(pie)
.enter()
.append("svg:g")
.attr("class", "slice");
arcs.append("svg:path")
.attr("fill", function(d, i) { return data[i].color; } )
.attr("d", arc);
arcs.append("svg:text")
.attr("transform", function(d) {
d.innerRadius = 0;
d.outerRadius = r;
return "translate(" + arc.centroid(d) + ")";
}).attr("text-anchor", "middle")
.text(function(d, i) { return data[i].label; });
}
chart.colors = function(value) {
if (!arguments.length) return colors;
colors = value;
return chart;
};
chart.width = function(value) {
if (!arguments.length) return w;
w = value;
return chart;
};
chart.height = function(value) {
if (!arguments.length) return h;
h = value;
return chart;
};
chart.loc = function(value) {
if (!arguments.length) return loc;
loc = value;
return chart;
};
return chart;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment