D3js来自csv文件的缩放线和点不会为点工作

时间:2015-03-03 15:48:22

标签: javascript csv d3.js

我正在尝试从http://bl.ocks.org/mbostock/4015254修改Zoomable区域,并在其中添加csv文件中的数据点,但无法解决问题。只有线条可以缩放和移动,但不能点。

我的猜测是我需要将圆圈的.attr("transform", function(d){ return "translate("+x(d[key0])+","+y(d[key1])+")";});放在函数绘制中,但是它无法识别key0key1(我在csv文件中有多个列) 。

以下是我修改过的代码。知道如何解决这个问题吗?

<script>
var margin = {top: 20, right: 60, bottom: 30, left: 20},
width = 960 - margin.left - margin.right,
height = 800 - margin.top - margin.bottom;`

var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse,
formatDate = d3.time.format("%Y");

var x = d3.time.scale()
.range([0, width]);

var y = d3.scale.linear()
.range([height, 0]);

var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");

var yAxis = d3.svg.axis()
.scale(y)
.orient("right")
.tickSize(-width)
.tickPadding(6);

var xGrid = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(-height,0)
.ticks(5)
.tickPadding(1)
.tickFormat("");

var line = d3.svg.line();

var zoom = d3.behavior.zoom()
.scaleExtent([1,128])
.on("zoom", draw);

var zoom2 = d3.behavior.zoom()
.scaleExtent([1,128])

var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);

svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + width + ",0)");

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height/2 + ")");

svg.append("g")
.attr("class", "x line")
.attr("transform", "translate(0," + height/2 + ")")
.append("svg:line")
    .attr("x1",x(0))
    .attr("y1",-y(0))
    .attr("x2",x(width))
    .attr("y2",-y(0));

svg.append("g")
.attr("class", "grid")
.attr("transform", "translate(0,"+ height + ")");

svg.append("path")
.attr("class", "line");

svg.append("rect")
.attr("class", "pane")
.attr("width", width)
.attr("height", height);

circle = svg.selectAll("circle");

d3.csv("encounter.csv", function(error, data) {

key0 = Object.keys(data[0])[1];
key1 = Object.keys(data[0])[3];

data.forEach(function(d,i) {
  d[key0] = parseDate(d[key0]);
  d[key1] = +d[key1];
});

x.domain([new Date(2014, 0, 1), new Date(2015, 0, 1)]);
y.domain(d3.extent(data, function(d){return d[key1];})).nice();
zoom.x(x);
svg.select("path.line").data([data]);
line.x(function(d) { return x(d[key0]); })
    .y(function(d) { return y(d[key1]); });

circle.data(data)
    .enter().append("circle")
    .attr("class", "dot")
    .attr("r", 5)
    .attr("transform", function(d){ return "translate("+x(d[key0])+","+y(d[key1])+")";});

draw();
});

function draw() {
  svg.select("g.x.axis").call(xAxis);
  svg.select("g.y.axis").call(yAxis);
  svg.select("g.grid").call(xGrid);
  svg.select("path.line").attr("d", line);
}

0 个答案:

没有答案