Created
February 1, 2013 17:01
-
-
Save jsuar/4692587 to your computer and use it in GitHub Desktop.
d3 packing example with squares and text.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<body> | |
<style> | |
circle, rect { | |
stroke: #000; | |
fill-opacity: .1; | |
} | |
text { | |
color:black; | |
} | |
</style> | |
<script src="http://mbostock.github.com/d3/d3.js?2.7.1"></script> | |
<script src="http://mbostock.github.com/d3/d3.layout.js?2.7.1"></script> | |
<script> | |
var data = { | |
children: [ | |
{value: 1}, | |
{value: 2}, | |
{value: 3}, | |
{value: 4}, | |
{value: 5}, | |
{value: 6}, | |
{value: 7}, | |
{value: 8}, | |
{value: 9}, | |
{value: 10}, | |
] | |
}; | |
var width = 960, | |
height = 500; | |
var pack = d3.layout.pack() | |
.sort(d3.descending) | |
.size([width, height]); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height) | |
.append("g"); | |
var elemEnter = svg.data([data]).selectAll(".node") | |
.data(pack.nodes) | |
.enter() | |
.append("g"); | |
elemEnter.append("circle") | |
.attr("class", "node") | |
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }) | |
.attr("r", function(d) { return d.r; }) | |
elemEnter.append("rect") | |
.attr("class", "node") | |
.attr("transform", function(d) { | |
return "translate(" + (d.x-d.r/Math.sqrt(2)) + "," + (d.y-d.r/Math.sqrt(2)) + ")"; }) | |
.attr("width", function(d) { return d.r*Math.sqrt(2) }) | |
.attr("height", function(d) { return d.r*Math.sqrt(2) }); | |
elemEnter.append("text") | |
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }) | |
.text(function(d){return d.value;}) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment