[ Launch Inlet ]
-
-
Save trtg/3892129 to your computer and use it in GitHub Desktop.
plotting line paths with d3
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
{"endpoint":"","display":"svg","public":true,"require":[],"tab":"edit","display_percent":0.7,"play":false,"loop":false,"restart":false,"autoinit":true,"pause":true,"loop_type":"period","bv":false,"nclones":15,"clone_opacity":0.4,"duration":3000,"ease":"linear","dt":0.01} |
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
var svg = d3.select("svg"); | |
var data = [ | |
{x:0,y:0}, | |
{x:10,y:10}, | |
{x:20,y:0}, | |
{x:30,y:10}, | |
{x:40,y:20}, | |
{x:50,y:60}, | |
{x:60,y:30}, | |
{x:143,y:52}, | |
{x:143, y:20}, | |
]; | |
var line = d3.svg.line() | |
.x(function(d){ | |
return d.x; | |
}) | |
.y(function(d){ | |
return d.y; | |
}); | |
//offset with respect to top left corner | |
var tx = 150; | |
var ty = 100; | |
var group = svg.append("g") | |
.attr("transform","translate("+[tx,ty]+")") | |
var path = group.selectAll("path") | |
.data([data]) | |
.enter() | |
.append("path") | |
.attr({ | |
d: line, | |
fill:"none", | |
stroke: "#000" | |
}) | |
//in the code above d:line is shorthand/ | |
//equivalent to d:function(d){return line(d)} | |
var text = group.append("text") | |
.attr("transform","translate("+[0,-20]+")") | |
.text(line(data)) | |
//we need to subtract the tx and ty offsets | |
//because the output of d3.mouse is with respect | |
//to the upper left corner but the svg path | |
//was translated to start down and over | |
//by ty,tx | |
svg.on("click",function(){ | |
var p = d3.mouse(this); | |
data.push({x:p[0]-tx,y:p[1]-ty}) | |
//updating the array in the previous | |
//step won't actually alter the graph | |
//you need to redraw the path with the | |
//newly added datapoint in the line below | |
path.attr("d",line); | |
//update the text on every click | |
text.text(line(data)); | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment