Last active
April 5, 2017 09:14
-
-
Save gujc71/0e32a00711e2cc680620692b4cf704da to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
svg { | |
border: 1px solid; | |
} | |
.bar { | |
fill: skyblue; | |
} | |
.bar:hover { | |
fill: blue; | |
} | |
.text { | |
fill: white; | |
font-weight:bold; | |
} | |
.grid line { | |
stroke: lightgrey; | |
stroke-opacity: 0.7; | |
} | |
</style> | |
<svg width="500" height="300"></svg> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script> | |
// grid | |
var dataset = [{x:'A', y:9 }, {x:'B', y:19}, {x:'C', y:29}, {x:'D', y:39}, | |
{x:'E', y:29}, {x:'F', y:19}, {x:'G', y:9 }]; | |
var svg = d3.select("svg"); | |
var width = parseInt(svg.style("width"), 10) -30; | |
var height = parseInt(svg.style("height"), 10)-20; | |
var svgG = svg.append("g") | |
.attr("transform", "translate(30, 0)"); | |
var xScale = d3.scaleBand() | |
.domain(dataset.map(function(d) { return d.x;} )) | |
.range([0, width]).padding(0.2); | |
var yScale = d3.scaleLinear() | |
.domain([0, d3.max(dataset, function(d){ return d.y; })]) | |
.range([height, 0]); | |
svgG.append("g") | |
.attr("class", "grid") | |
.attr("transform", "translate(0," + height + ")") | |
.call(d3.axisBottom(xScale) | |
.tickSize(-height) | |
); | |
svgG.append("g") | |
.attr("class", "grid") | |
.call(d3.axisLeft(yScale) | |
.ticks(5) | |
.tickSize(-width) | |
); | |
svgG.selectAll("rect") | |
.data(dataset) | |
.enter().append("rect") | |
.attr("class", "bar") | |
.attr("height", function(d, i) {return height-yScale(d.y)}) | |
.attr("width", xScale.bandwidth()) | |
.attr("x", function(d, i) {return xScale(d.x)}) | |
.attr("y", function(d, i) {return yScale(d.y)}); | |
svgG.selectAll("text") | |
.data(dataset) | |
.enter().append("text") | |
.text(function(d) {return d.y}) | |
.attr("class", "text") | |
.attr("x", function(d, i) {return xScale(d.x)+xScale.bandwidth()/2}) | |
.style("text-anchor", "middle") | |
.attr("y", function(d, i) {return yScale(d.y) + 15}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment