<html>
<style>
.axis path,
.axis line{
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
path {
fill: transparent;
stroke: green;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var width = 400; //画布的宽度
var height = 300; //画布的高度
var svg = d3.select("body") //选择文档中的body元素
.append("svg") //添加一个svg元素
.attr("width", width) //设定宽度
.attr("height", height); //设定高度
var xlinear = d3.scale.linear()
.domain([-150, 150])
.range([0, 300]);
var ylinear = d3.scale.linear()
.domain([0, 250])
.range([250, 0]);
var xaxis = d3.svg.axis()
.scale(xlinear) //指定比例尺
.orient("bottom") //指定刻度的方向
.ticks(10); //指定刻度的数量
var yaxis = d3.svg.axis()
.scale(ylinear)
.orient("left")
.ticks(5);
svg.append("g")
.attr("class","axis")
.attr("transform","translate(0,250)") //x轴上下平移不会对坐标系造成影响
.call(xaxis);
svg.append("g")
.attr("class","axis")
.attr("transform","translate(150,0)") //y轴左右平移不会对坐标系造成影响
.call(yaxis);
var dataset = [
{x: -150, y: 0}, {x: -100, y: 50},
{x: -50, y: 100}, {x: 0, y: 150},
{x: 50, y: 200}, {x: 100, y: 250},
{x: 150,y:250}
];
// 添加折线
var line = d3.svg.line()
.x(function(d) {
return xlinear(d.x)
})
.y(function(d) {
return ylinear(d.y)
})
// 选择线条的类型
.interpolate('linear');
// 添加path元素,并通过line()计算出值来赋值
svg.append('path')
.attr('stroke-width', 2)
.attr('d', line(dataset));
</script>
</body>
</html>
D3 折线图
最新推荐文章于 2024-01-09 15:01:39 发布