用d3线段画坐标轴

时间:2023-02-13 05:59:01

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.axis path,.axis line{
fill:none;
stroke: black;
shape-rendering: crispEdges;
}

.axis text{
font-family: sans-serif;
font-size:11px;
}

</style>
</head>
<body>
<script type="text/javascript" src = "http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript">
var width = 600;
var height = 600;
var svg = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height);
//用于坐标轴的线性比例尺
var xScale = d3.scale.linear()
.domain([0,10])
.range([0,300]);
//定义坐标轴
var axis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
var gAxis = svg.append("g")
.attr("transform","translate(80,80)")
.attr("class","axis")
//axis(gAxis);
gAxis.call(axis);
</script>
</body>
</html>

运行结果如下图所示:

用d3线段画坐标轴

2.画刻度

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.axis path,.axis line{
fill:none;
stroke:black;
shape-rendering:crispEdges;
}

.axis text{
font-family:sans-serif;
font-size:11px;
}

</style>
</head>
<body>
<script type="text/javascript" src = "http://d3js.org/d3.v3.min.js" charset = "utf-8"></script>
<script type="text/javascript">
var width = 600;
var height = 600;
var svg = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height);
var scale = d3.scale.linear()
.domain([0,10])
.range([0,300]);
var axisLeft = d3.svg.axis()
.scale(scale)
.orient("left")
.ticks(5);
var axisRight = d3.svg.axis()
.scale(scale)
.orient("right")
.tickValues([3,4,5,6,7]);
var gAxis = svg.append("g")
.attr("transform","translate(80,80)");
var gYxis = svg.append("g")
.attr("transform","translate(180,80)");
gAxis.attr("class","axis");
gYxis.attr("class","axis");
gAxis.call(axisLeft);
gYxis.call(axisRight);
</script>
</body>
</html>

运行结果如下图所示:

用d3线段画坐标轴