Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
7
rated 0 times [  13] [ 6]  / answers: 1 / hits: 43528  / 13 Years ago, fri, december 16, 2011, 12:00:00

I have the following simple line in d3 but haven't an issue trying to figure out how to pass it data2 and update the line to reflect the change.



<!DOCTYPE html>
<html lang=en>
<head>
<title>D3 Line Chart Demo</title>
<meta charset=utf-8 />
<meta http-equiv=Content-Type content=text/html; charset=UTF-8/>

<link rel=stylesheet type=text/css href=style.css>

<script src=jquery.min.js type=text/javascript charset=utf-8></script>
<script src=d3.min.js type=text/javascript charset=utf-8></script>
<body>
<button class=first last onclick=transition()>
Update
</button>
<div id=chart></div>
</body>

<script>

var data = [3, 7, 9, 1, 4, 6, 8, 2, 5];
var data2 = [3, 7, 9, 1, 4, 6, 8, 2, 15];
var width = 600;
var height = 400;
var max = d3.max(data);

x = d3.scale.linear().domain([0, data.length - 1]).range([0, width]);
y = d3.scale.linear().domain([0, max]).range([height, 0]);

vis = d3.select('#chart')
.style('margin', '20px auto')
.style('width', + width + px)
.append('svg:svg')
.attr('width', width)
.attr('height', height)
.attr('class', 'viz')
.append('svg:g');

vis.selectAll('path.line')
.data([data])
.enter()
.append(svg:path)
.attr(d, d3.svg.line().x(function(d, i) {
return x(i);
})
.y(y));
</script>
</html>

More From » d3.js

 Answers
9

I am new to D3 but this is what I have found and I mainly figured this out from the sparklines example here.



Instead of drawing the line with this code:



vis.selectAll('path.line')
.data([data])
.enter()
.append(svg:path)
.attr(d, d3.svg.line().x(function(d, i) {return x(i); }).y(y));


generate the line separately:



 var line = d3.svg.line().x(function(d, i) { return x(i); }).y(y)


Then apply it to the data:



vis.selectAll('path.line')
.data([data])
.enter()
.append(svg:path)
.attr(d, line);


Then when you want to update the data you call:



 vis.selectAll(path)
.data([data]) // set the new data
.attr(d, line); // apply the new data values


The sparklines example also shows you how to animate it :)


[#88519] Thursday, December 15, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kalias

Total Points: 79
Total Questions: 116
Total Answers: 116

Location: Malaysia
Member since Wed, May 11, 2022
2 Years ago
kalias questions
Fri, May 27, 22, 00:00, 2 Years ago
Thu, Jan 20, 22, 00:00, 2 Years ago
Fri, Jul 30, 21, 00:00, 3 Years ago
Sun, Aug 2, 20, 00:00, 4 Years ago
;