Reputation: 353
I was working with the d3.js simple line graph example and was wondering how to dynamically adjust the domain for the x and y axis so that if the data is updated, the graph can be adjusted to fit the new line. here is the current code (I think) that sets these domains.
var x = d3.scale.linear().domain([-15, 15]).range([0, w]);
var y = d3.scale.linear().domain([0, 120]).range([h, 0]);
Currently the domain values are arbitrary. the vairables w and h are the width and the height of the svg element.
Any help would be appreciated.
Upvotes: 1
Views: 1638
Reputation: 4874
I would start by setting the lower and upper bounds of your domain to dynamic values, calculated from your data set. Depending on the structure or your data, d3 has max
and min
methods that will calculate the max / min values in an array of values.
var x = d3.scale.linear().domain([d3.min(data), d3.max(data)]).range([0,w]);
If you have some method to update your data, you can add functionality to then redefine x
(you might want to attach x
to some sort of namespace that is accessible throughout the entire scope of your function) and then recall your line generator (via d3.svg.line()
).
Seeing your comments, let me clarify.
There are several different ways that you can do this, since d3 is such a low-level library (which I personally think is part of the appeal). In my own work, I use multiple series which conveniently allows me to use the common enter, update and exit model that you see used with other chart types (like a bar chart). But in the most basic terms, here's what you need:
SVG:path
element with your datasetSVG:path
element and scales with new dataHere's a jsfiddle that demonstrates this, adding new random data every seconds for 10 seconds.
Upvotes: 1