D3js學習一


<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Graph</title>
<style type = "text/css">
body{ font: 12px Arial;}
path{
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line{
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}


.grid .tick {
stroke: lightgrey;
opacity: 0.7;
}
.grid path {
stroke-width: 0;
}

.area{
fill: lightsteelblue;
stroke-width: 0;
}

</style>
<script type="text/javascript" src="d3.v3.min.js"></script>
</head>
<body>

<script type="text/javascript">

var margin = {top:30, right:20, bottom: 30, left: 50};
width = 600 - margin.left -margin.right;
height = 270 - margin.top - margin.bottom;

//為了將數據中時間轉化為D3需要的樣式
var parseDate = d3.time.format("%d-%b-%y").parse;

var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

//ticks只是你建議的,真正畫圖時,D3會自己決定這個應該分為幾個刻度。
var xAxis = d3.svg.axis().scale(x).orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y).orient("left").ticks(5);


var valueline = d3.svg.line()
.x(function(d){return x(d.date);})
.y(function(d){return y(d.close);});

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

//這是划線需要的,可以有很多的模式,monotone,basic。。。想要更改不同樣式的同學可以在網上找找。
var valueline = d3.svg.line()
.interpolate("monotone")
.x(function(d){return x(d.date);})
.y(function(d){return y(d.close);});

//這是自己寫的死數據

//Get the data
var data_ = [
{date:parseDate("1-May-12"),close:582.13},
{date:parseDate("30-Apr-12"),close:100.98},
{date:parseDate("27-Apr-12"),close:603.00},
{date:parseDate("26-Apr-12"),close:100.70},
{date:parseDate("25-Apr-12"),close:610.00},
{date:parseDate("24-Apr-12"),close:100.28},
{date:parseDate("23-Apr-12"),close:571.70},
{date:parseDate("20-Apr-12"),close:100.98},
{date:parseDate("19-Apr-12"),close:587.44},
{date:parseDate("18-Apr-12"),close:100.34},
{date:parseDate("17-Apr-12"),close:609.70},
{date:parseDate("16-Apr-12"),close:100.13}
]

//Scale(規模) the range of the data
x.domain(d3.extent(data_, function(d){
return d.date;
}));
y.domain([0, d3.max(data_, function(d){
return d.close;
})]);

//Add the valueline path
svg.append("path")
.attr("d", valueline(data_));


//Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
//Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);



</script>
</body>
</html>

這是最基本的一個圖表,有橫坐標,縱坐標。

效果如下:

 

這是最基本的圖形,x軸,y軸,對應的數據形式是JSON類型,更多的可以參照D3官網: http://d3js.org/  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM