I have the following data:
parseDate = d3.time.format("%Y").parse,
format = d3.time.format("%Y");
var myData = [
{ dataField: "A", coords: [
{xCoord: parseDate('1990') , yCoord: Math.random() * 100},
{xCoord: parseDate('1991') , yCoord: Math.random() * 100},
{xCoord: parseDate('1992') , yCoord: Math.random() * 100},
{xCoord: parseDate('1993') , yCoord: Math.random() * 100},
{xCoord: parseDate('1994') , yCoord: Math.random() * 100},
{xCoord: parseDate('1995') , yCoord: Math.random() * 100},
{xCoord: parseDate('1996') , yCoord: Math.random() * 100},
{xCoord: parseDate('1997') , yCoord: Math.random() * 100},
{xCoord: parseDate('1998') , yCoord: Math.random() * 100},
{xCoord: parseDate('1999') , yCoord: Math.random() * 100}
]
},
{ dataField: "B",coords: [
{xCoord: parseDate('1990') , yCoord: Math.random() * 100},
{xCoord: parseDate('1991') , yCoord: Math.random() * 100},
{xCoord: parseDate('1992') , yCoord: Math.random() * 100},
{xCoord: parseDate('1993') , yCoord: Math.random() * 100},
{xCoord: parseDate('1994') , yCoord: Math.random() * 100},
{xCoord: parseDate('1995') , yCoord: Math.random() * 100},
{xCoord: parseDate('1996') , yCoord: Math.random() * 100},
{xCoord: parseDate('1997') , yCoord: Math.random() * 100},
{xCoord: parseDate('1998') , yCoord: Math.random() * 100},
{xCoord: parseDate('1999') , yCoord: Math.random() * 100}
]
}
and I am trying to create a line graph using d3. Additionally, I have the code:
var data = function (d) { return d.coords; };
var xValue = function (d) { return d.xCoord; };
var yValue = function (d) { return d.yCoord; };
I have been creating my scale as such:
xScale = d3.time.scale()
.domain([new Date(1988,10,30),new Date(2000,01,30)])
.range([margin.left, 600 - margin.right]);
However, my goal is to have my domain adjust itself to be the smallest year to the largest year (or mabye even extending an extra year in each direction). But so far, I have been unsuccessful. I have attempted to use
.domain(d3.extent(data, xValue));
But haven't had luck. I'm fairly new to javascript and think my struggles lie within the way I stored my data. Any ideas would be great.
You can use the built in d3.extent function to get the min and max of an array. It takes an an array and an optional accessor function. It will return an array of 2 values, the min and max:
[min, max]
I would try
xScale.domain(d3.extent(myData[0].coords, function(d) {return d.xCoord; }));
and then rinse and repeat for the other data labels You could do it in a for
loop if there are a bunch of different data sets.