我上周开始学习d3.js,我正在尝试创建一个散点图。我期待y轴上的t1,t2,t3,t4,t5。而x-anxis是从1到最大的质量值。但在运行下面的代码后,看起来点的位置不正确。其中两个甚至超出了y aix的范围。我无法弄清楚原因。任何人都可以帮助修复代码并解释原因吗?提前谢谢!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dot Plot</title>
<style>
.axis path,
.axis line{
fill: none;
stroke: #000;
shape-rendering: crishpEdges;
}
.circles { opacity: .7; }
</style>
</head>
<body>
<h1 style = "text-align:center;">Dot Plot Example</h1>
</body>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var data = [
{"custid": 1, "Type": "t1","quality": 7},
{"custid": 2, "Type": "t2", "quality": 2},
{"custid": 3, "Type": "t3", "quality": 3},
{"custid": 4, "Type": "t4", "quality": 7},
{"custid": 5, "Type": "t5", "quality": 2}
];
data.forEach(function(d){
d.quality = +d.quality;
d.Type = d.Type;
return console.log(data);
})
var margin = {t:30, r:20, b:40, l:40 },
w = 600 - margin.l - margin.r,
h = 500 - margin.t - margin.b;
var color = d3.scale.category20c();
var x = d3.scale.linear()
.range([0, w])
.domain([0,d3.max(data, function(d){return d.quality})]);
var y = d3.scale.ordinal()
.range([h,0])
.domain(data.map(function(d){return d.Type;}));
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(8);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(6);
var svg = d3.select("body")
.append("svg")
.attr("width", w + margin.l + margin.r)
.attr("height", h + margin.t + margin.b)
.style("margin-left", "auto")
.style("margin-right", "auto")
.style("display", "block")
.append("g")
.attr("transform", "translate(" + margin.l + "," + margin.t + ")");
svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("class", "circles")
.attr({
cx: function(d) { return x(d.quality); },
cy: function(d) { return y(d.Type); },
r: 8
})
.style("fill", function(d){return color(d.Type);});
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(" + margin.l + "," + (h - 20 + margin.t) + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + margin.l + "," + margin.t + ")")
.call(yAxis);
</script>
</body>
</html>
答案 0 :(得分:1)
有两个问题。首先,使用它时的序数比例要求域和范围元素之间的1:1映射。也就是说,对于赋予.range()
的数组中的每个元素,需要在给予.domain()
的数组中有相应的元素。在您的情况下,您有5个域值,但只有2个范围值。在这种情况下,您应该使用.rangeRoundPoints()
,它会根据域中的值数自动细分间隔:
var y = d3.scale.ordinal()
.rangeRoundPoints([h,0])
.domain(data.map(function(d){return d.Type;}));
其次,您正在通过边距翻译轴的容器,但不包括点的容器。你只需要
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
完整示例here。