问题
I am a total beginner to d3.js so please be kind :)
considering this jsbin example
I have the following dataset:
var dataset = [ [d3.time.hour.utc.offset(now, -5), 1, 10], [d3.time.hour.utc.offset(now, -4), 2, 20], [d3.time.hour.utc.offset(now, -3), 3, 30], [d3.time.hour.utc.offset(now, -2), 4, 40], [d3.time.hour.utc.offset(now, -1), 5, 50], [now, 6, 60], ];
Two questions.
Does d3 provide a better approach to finding the max value for my y-axis data (all columns but the 0th, the 0th column is x-axis (time)) in my dataset array? Currently I am just looping through the entire dataset array and making a second array, excluding the first column. Perhaps there is a better datastructure other than an array I should be using for this entirely?
var data_arr = []; for (row in dataset){ for (col=1;col < dataset[row].length; col++){ data_arr.push(dataset[row][col]); } } var yScale = d3.scale.linear() .domain([0, d3.max(data_arr)]) .range([h - padding, padding]);Once thats resolved, I still need to determine how to graph multiple y-axis values in general! This worked fine before I needed multiple y-axis values:
svg.selectAll("circle") .data(dataset) .enter() .append("circle") .attr("cx", function(d) { return xScale(d[0]); }) .attr("cy", function(d) { return yScale(d[1]); }) .attr("r", 2);
Please take a look at the graph w/ code here now for full context: http://jsbin.com/edatol/1/edit Any help is appreciated!
回答1:
I've made a couple of changes to your example and you can see the results at http://jsbin.com/edatol/2/edit.
First, I modified your data a little bit. This is mostly just a style thing, but I find it's easier to work with objects instead of arrays:
//Static dataset
var dataset = [
{x: d3.time.hour.utc.offset(now, -5), y1: 1, y2: 10},
{x: d3.time.hour.utc.offset(now, -4), y1: 2, y2: 20},
{x: d3.time.hour.utc.offset(now, -3), y1: 3, y2: 30},
{x: d3.time.hour.utc.offset(now, -2), y1: 4, y2: 40},
{x: d3.time.hour.utc.offset(now, -1), y1: 5, y2: 50},
{x: now, y1: 6, y2: 60},
];
Then you can find your domains and ranges like this:
var xDomain = d3.extent(dataset, function(i) { return i.x; });
var maxY = d3.max(dataset, function(i) { return Math.max(i.y1, i.y2); });
Then to add multiple y-values, you just have to append an additional circle with the appropriate values. I gave them different classes so that you can use that to select them if you want to do transitions or updates later on.
//Create circles
svg.selectAll(".y1")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function(d) { return xScale(d.x); })
.attr("cy", function(d) { return yScale(d.y1); })
.attr("class", "y1")
.attr("r", 2);
//Create circles
svg.selectAll(".y2")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function(d) { return xScale(d.x); })
.attr("cy", function(d) { return yScale(d.y2); })
.attr("class", "y2")
.attr("r", 2);
来源:https://stackoverflow.com/questions/12732487/d3-js-dataset-array-w-multiple-y-axis-values