我对 d3.js 很陌生,我正在尝试在散点图顶部添加一条线。我有两个要绘制的数据集
var data = [ {
"x" : 30,
"y" : 30,
"r" : 20,
"c" : "green",
"s" : "s1"
}, {
"x" : 70,
"y" : 70,
"r" : 20,
"c" : "purple",
"s" : "s2"
}, {
"x" : 110,
"y" : 100,
"r" : 20,
"c" : "red",
"s" : "s3"
} ];
var data1 = [{
"x":30,
"y":30},
{"x":70,
"y":70}];
数据变量用作散点系列,在同一张图表上,我想将第二个数据集绘制为线系列。
var margin = {
top : 20,
right : 20,
bottom : 30,
left : 40
}, width = 960 - margin.left - margin.right, height = 500 - margin.top
- margin.bottom;
var x = d3.scale.linear().range([ 0, width ]);
var y = d3.scale.linear().range([ height, 0 ]);
var color = d3.scale.category10();
var xAxis = d3.svg.axis().scale(x).orient("bottom");
var yAxis = d3.svg.axis().scale(y).orient("left");
var svg = d3.select("#"+div).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 + ")");
var data = [ {
"x" : 30,
"y" : 30,
"r" : 20,
"c" : "green",
"s" : "s1"
}, {
"x" : 70,
"y" : 70,
"r" : 20,
"c" : "purple",
"s" : "s2"
}, {
"x" : 110,
"y" : 100,
"r" : 20,
"c" : "red",
"s" : "s3"
} ];
var data1 = [{
"x":30,
"y":30},
{"x":70,
"y":70}];
x.domain(d3.extent(data, function(d) {
return d.x;
})).nice();
y.domain(d3.extent(data, function(d) {
return d.y;
})).nice();
svg.append("g").attr("class", "x axis").attr("transform",
"translate(0," + height + ")").call(xAxis).append("text").attr(
"class", "label").attr("x", width).attr("y", -6).style(
"text-anchor", "end").text("Yield");
svg.append("g").attr("class", "y axis").call(yAxis).append("text")
.attr("class", "label").attr("transform", "rotate(-90)").attr(
"y", 6).attr("dy", ".71em").style("text-anchor", "end")
.text("Skew")
var line = d3.svg.line()
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });
svg.selectAll(".line").data(data1).enter().append("path").attr("class","line").attr("d",line);
svg.selectAll(".dot").data(data).enter().append("circle").attr("class",
"dot").attr("r", 3.5).attr("cx", function(d) {
return x(d.x);
}).attr("cy", function(d) {
return y(d.y);
}).style("fill", function(d) {
return color(d.c);
});
var legend = svg.selectAll(".legend").data(color.domain()).enter()
.append("g").attr("class", "legend").attr("transform",
function(d, i) {
return "translate(0," + i * 20 + ")";
});
legend.append("rect").attr("x", width - 18).attr("width", 18).attr(
"height", 18).style("fill", color);
legend.append("text").attr("x", width - 24).attr("y", 9).attr("dy",
".35em").style("text-anchor", "end").text(function(d) {
return d;
});
但我根本看不到画线。