d3.js学习10----折线图的制作

一切尽在注释中………………

ZheXian

     

 

var dataset=[5,3,1,5,2,4,2];

varxMarks=['Mon','Tues','Wed','Thur','Fri','Sat','Sun'];

var w=600;

var h=400;

var title="Beijing";

var subTitle="temperature";

 

//定义画布

var svg=d3.select("body")

.append("svg")

.attr("width",w)

.attr("height",h);

 

//添加标题

svg.append("g")

.append("text")

.text(title)

.attr("class","title")

.attr("x",220)

.attr("y",20);

 

//添加副标题

svg.append("g")

.append("text")

.text(subTitle)

.attr("class","subTitle")

.attr("x",220)

.attr("y",40);

 

//横坐标轴比例尺

var xScale = d3.scale.linear()

.domain([0,dataset.length-1])

.range([60,400]);//这个range相当于横轴的左右平移

//纵坐标轴比例尺

var yScale = d3.scale.linear()

.domain([0,d3.max(dataset)])

.range([220,60]);

//定义横轴网格线

var xInner = d3.svg.axis()

.scale(xScale)

.tickSize(-160,0,0)//调整网格线长度

.orient("bottom")

.ticks(dataset.length);

//添加横轴网格线

svg.append("g")

.attr("class","inner_line")

.attr("transform","translate(0," + 220 + ")")

//用来把纵的网格线上移的

.call(xInner)

.selectAll("text")

.text("");

//定义纵轴网格线

var yInner = d3.svg.axis()

.scale(yScale)

.tickSize(-340,0,0)

.tickFormat("")

.orient("left")

.ticks(5);

//添加纵轴网格线

var yBar=svg.append("g")

.attr("class","inner_line")

.attr("transform","translate("+60+",0)")

.call(yInner);

//定义横轴

var xAxis = d3.svg.axis()

.scale(xScale)

.orient("bottom")

.ticks(dataset.length);

//添加横坐标轴并通过编号获取对应的横轴标签

var xBar=svg.append("g")

.attr("class","axis")

.attr("transform","translate(0," + 220 + ")")//用来上下平移横轴位置

.call(xAxis)

.selectAll("text")

.text(function(d){return xMarks[d];});

//定义纵轴

var yAxis = d3.svg.axis()

.scale(yScale)

.orient("left")

.ticks(5);//这个是细分度

//添加纵轴

var yBar=svg.append("g")

.attr("class", "axis")

.attr("transform","translate("+60+",0)")

.call(yAxis);

//添加折线

var line = d3.svg.line()

.x(function(d,i){return xScale(i);})

.y(function(d){return yScale(d);});

var path=svg.append("path")

.attr("d", line(dataset))

.style("fill","#F00")

.style("fill","none")

.style("stroke-width",1)

.style("stroke","#09F")

.style("stroke-opacity",0.9);

//添加系列的小圆点

svg.selectAll("circle")

.data(dataset)

.enter()

.append("circle")

.attr("cx", function(d,i) {

return xScale(i);

})

.attr("cy", function(d) {

return yScale(d);

})

.attr("r",5)

.attr("fill","#09F");

 

 

Css文件代码:

 

body{

height: 100%;

}

.title{font-family:Arial,微软雅黑;font-size:18px;text-anchor:middle;}

.subTitle{font-family:Arial,宋体;font-size:12px;text-anchor:middle;fill:#666}

.axis path,

.axis line {

fill: none;

stroke: black;

shape-rendering: crispEdges;

}

.axis text {

font-family: sans-serif;

font-size: 11px;

fill:#999;

}

.inner_line path,

.inner_line line {

fill: none;

stroke:#E7E7E7;

shape-rendering: crispEdges;

}

d3.js学习10----折线图的制作_第1张图片

你可能感兴趣的:(数据可视化)