Skip to content

Instantly share code, notes, and snippets.

@AndrewStaroscik
Last active December 15, 2015 07:29
Show Gist options
  • Save AndrewStaroscik/5223431 to your computer and use it in GitHub Desktop.
Save AndrewStaroscik/5223431 to your computer and use it in GitHub Desktop.
add the same functions to an svg shape and label in d3
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: auto;
position: relative;
width: 960px;
}
text {
font: 10px sans-serif;
}
</style>
<body>
<div id="vis"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var dataset = [
{name: "Path 1", centerX: 0, values: []},
{name: "Path 2", centerX: 0, values: []}
];
var width = 500,
height = 200;
var color = d3.scale.category20();
var line = d3.svg.line()
.x(function(d) {return d.x })
.y(function(d) {return d.y });
var svg = d3.select("#vis").append("svg")
.attr("width", width)
.attr("height", height);
updatePaths(); // run for the first time
updateView(); // run for the first time
function updateView() {
var g = svg.selectAll(".shape")
.data(dataset);
var gEnter = g.enter()
.append("g")
.attr("class", "shape")
.on("click", change);
gEnter
.append("path")
.attr("d", function(d) { return line(d.values) + "Z"; })
.style("fill", function(d, i) { return color(i); });
gEnter
.append("text")
.attr("x", function(d) { return d.centerX; })
.attr("y", 100)
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.name; });
var gTransition = g.transition().duration(500);
gTransition
.selectAll("path")
.attr("d", function(d) { return line(d.values) + "Z"; });
gTransition
.selectAll("text")
.attr("x", function(d) { return d.centerX; });
}
function change() {
updatePaths();
updateView();
}
// data updating function to draw custom paths each time the change button is pushed
function updatePaths() {
var i,
firstX = Math.random() * 50 + 100,
secondX = Math.random() * 100 + 300;
dataset[0].values = [];
dataset[1].values = [];
dataset[0].centerX = firstX;
dataset[1].centerX = secondX;
for(i = 0; i < 10; i += 1) {
dataset[0].values.push({x: firstX + (Math.random() * 40 + 20) * Math.sin((Math.PI / 180) * i * 360 / 9), y: 100 + (Math.random() * 60 + 20) * Math.cos((Math.PI / 180) * i * 360 / 9)})
}
for(i = 0; i < 6; i += 1) {
dataset[1].values.push({x: secondX + (Math.random() * 80 + 30) * Math.sin((Math.PI /180) * i * 360 / 5), y: 100 + (Math.random() * 60 + 30) * Math.cos((Math.PI / 180) * i * 360 / 5)})
}
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment