html部分:html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/d3.js"></script>
<style>
svg{
background-color: aqua;
}
</style>
<script src="d3.js"></script> //引入d3.js,按照實際的路徑
<script src="jquery-1.11.3.js"></script> //引入jquery,按照實際路徑
</head>
<body>
<div style="position: absolute;width: 100%;height: 100%">
<div id=tu1 style="width: 48%;height: 100%;float: left;"></div>
<div id=tu2 style="width: 48%;height: 100%;float: left;"></div>
</div>
</body>
</html>
//d3部分:
<script>
//定義數據
var dataset=[100,200,300,180,240,500,230]
var xdata1=['週一','週二','週三','週四','週五','週六','週日']
var xdata2=['班級A','班級B','班級C','班級D',]
var ydata2=[1000,2000,3000,1400]
function drawbar(divname,xdata,ydata,bool) {
//1.定義svg寬及高
var svgwidth = $("#"+divname).width();
var svgheight = $("#"+divname).height();
//2.生成svg
var _svg = d3.select("#"+divname)
.append("svg")
.attr("width", svgwidth)
.attr("height", svgheight);
//3.定義繪圖區與svg四邊邊距
var margin = {"top": 0, "right": 0, "bottom": 50, "left": 50};
//4.定義繪圖區,存放到g組中
var gdraw1 = _svg.append("g")
.attr("id", "gdraw1")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//5.定義標題高度
var titleheight = 50;
//6.定義核心繪圖區
var gdraw2 = gdraw1.append("g")
.attr("id", "gdraw2")
.attr("transform", "translate(0," + titleheight + ")");
//7.定義圖與核心區之間的四邊邊距
var charmargin = {"top": 0, "right": 0, "bottom": 30, "left": 30};
//8.計算出主區域的寬和高
var mainwidth = svgwidth - margin.left - margin.right;
var mainheight = svgheight - margin.bottom - margin.top - titleheight;
//9.計算X軸和Y軸的寬及高
var xaxiswidth = mainwidth - charmargin.left - charmargin.right;
var yaxisheight = mainheight - charmargin.top - charmargin.bottom;
//10.定義存放x軸g組和存入y軸g組
//a.x軸
var gxaxis = gdraw2.append("g")
.attr("id", "gxaxis")
.attr("transform", "translate(0," + (yaxisheight + charmargin.top) + ")");
var scaleband = d3.scaleBand()
.domain(xdata)
.range([0, xaxiswidth])
.padding(0.2);
var xaxis = d3.axisBottom()
.scale(scaleband);
xaxis(gxaxis);
//b.y軸
var gyaxis = gdraw2.append("g")
.attr("id", "gyaxis")
.attr("transform", "translate(0," + charmargin.top + ")");
var scaleline = d3.scaleLinear()
.domain([0, d3.max(ydata)])
.range([yaxisheight, 0]);
var yaxis = d3.axisLeft()
.scale(scaleline);
yaxis(gyaxis);
//畫柱形圖
//顏色
var color = d3.scaleOrdinal()
.domain(d3.range(ydata.length))
.range(d3.schemeCategory10);
//添加G組
var gbar = gdraw2.append("g")
.attr("id", "gbar")
.attr("transform", "translate(0," + charmargin.top + ")")
gbar.selectAll("rect")
.data(ydata)
.ener()
.append("rect")
.attr("x", function (d, i) { return scaleband(xdata[i]) })
.attr("y",function(d,i){