如何定义静态x轴和y轴,javascript d3

时间:2013-09-17 10:03:01

标签: javascript d3.js

x轴和y轴取决于数组中给出的值,每个值都从值min开始,并在值max中停止。我们可以将分段更改为独立于用户值吗?

<!DOCTYPE html>
<meta charset="utf-8">
<style>

body {
font: 10px sans-serif;
}

.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}

.point {
 fill: steelblue;
stroke: #000;
}

</style>
<body>
<script src="http://d3js.org/d3.v2.js?2.9.6"></script>
<script>

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 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 + ")");

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

 // Coerce the strings to numbers.
data.forEach(function(d) {
d.x = +d.x;
d.y = +d.y;
});

// Compute the scales’ domains.
x.domain(d3.extent(data, function(d) { return d.x; })).nice();
y.domain(d3.extent(data, function(d) { return d.y; })).nice();

// Add the x-axis.
 svg.append("g")
.attr("class", "x axis")
 .attr("transform", "translate(0," + height + ")")
 .call(d3.svg.axis().scale(x).orient("bottom"));

// Add the y-axis.
svg.append("g")
.attr("class", "y axis")
 .call(d3.svg.axis().scale(y).orient("left"));

 // Add the points!
 svg.selectAll(".point")
 .data(data)
 .enter().append("path")
  .attr("class", "point")
  .attr("d", d3.svg.symbol().type("triangle-up"))
  .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
  });

 </script>

文件:data.cvs

x,y
5,90
25,30
45,50
65,55
85,25

1 个答案:

答案 0 :(得分:1)

我认为您询问是否可以设置自定义刻度范围,或者是否可以为每个轴设置自定义范围。好吧,答案是肯定的。

您可以使用axis.tickValues([custom range of values)]自定义刻度线。

您可以在域名调用中为轴设置自定义范围。您可以使用自定义范围[0,100],例如在vida.io上方发布,也可以在jsbin中使用,.domain([0,100])。在jsbin中,您可以通过其他几种方式自定义已注释掉的轴的范围。只需将它们打开并重新加载即可查看它们的作用。不要忘记在右上角用js击中跑道。

使用数据上的d3.extent返回评估者中指定的数组的最大值和最小值。

希望这能回答你的问题。