Skip to content

Instantly share code, notes, and snippets.

@eightHundreds
Last active January 28, 2017 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eightHundreds/72e418438de7bf803d567fd4ea7b6b4a to your computer and use it in GitHub Desktop.
Save eightHundreds/72e418438de7bf803d567fd4ea7b6b4a to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div id="container">
</div>
</body>
<script src="https://cdn.bootcss.com/d3/4.4.3/d3.min.js"></script>
<script src="index.js" type="text/javascript" charset="utf-8"></script>
</html>
window.onload=function(){
//areaGraph()
histogram()
}
function histogram(){
//http://bl.ocks.org/mbostock/3885304
var svgArea={width:500,height:250};
var margin={left:20,top:20,right:20,bottom:20}
,gArea={width:svgArea.width-margin.left-margin.right,height:svgArea.height-margin.top-margin.bottom};
var rectpadding=10
var data=[1,3,5,7,8,10];
var svg=d3.select('#container')
.append('svg')
.attr('width',svgArea.width)
.attr('height',svgArea.height)
var g=svg.append('g')
.attr('transform',"translate("+margin.left+","+margin.top+")")
//比例尺
var scale_x=d3.scaleBand()
.domain(data)
.rangeRound([0,gArea.width])
.padding(0.1)//v4中的新比例尺,整数比例尺
var scale_y=d3.scaleLinear().domain([0,d3.max(data)])
.rangeRound([gArea.height,0])//注意相反
//坐标轴生成器
var axis_x=d3.axisBottom(scale_x)
var axis_y=d3.axisLeft(scale_y)
//坐标轴
g.append('g')
.attr('transform',"translate(0,"+(gArea.height)+")")
.call(axis_x)
g.append('g')
.call(axis_y)
//矩形图
var rects=g.selectAll('.rect')
.data(data)
.enter()
.append('rect')
.attr('x',function(d,i){return scale_x(d)})
.attr('y',function(d){return scale_y(d)})//数据已经相反了
.attr('width',scale_x.bandwidth())
.attr('height',function(d,i){return gArea.height-scale_y(d);})
//矩形上的文本
var texts=g.selectAll('.rectText')
.data(data)
.enter()
.append('text')
.text(function(d,i){return d})
.attr('x',function(d,i){return scale_x(d)+scale_x.bandwidth()/2})
.attr('dx','-0.5em')
.attr('dy','1em')
.attr('y',function(d){return scale_y(d)})//数据已经相反了
}
#container{
background:#ddd;
width: 500px;
height: 250px;
font-family: arial;
}
#container path{
stroke: #111;
fill: none;
}
#container svg rect{
fill: steelblue;
}
#container svg rect:hover{
fill: darkred;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment