Skip to content

Instantly share code, notes, and snippets.

@thomaxyu001
Last active October 22, 2017 20:30
Show Gist options
  • Save thomaxyu001/4984aceb602c1e209768b19e0edb6585 to your computer and use it in GitHub Desktop.
Save thomaxyu001/4984aceb602c1e209768b19e0edb6585 to your computer and use it in GitHub Desktop.
fresh block_2
license: mit
<!DOCTYPE html>
<html lang="en">
<head>
<title>I'm Learning D3</title>
<script src="https://d3js.org/d3.v4.js" charset="utf-8"></script>
<style>
text {
font-family: "Open Sans", sans-serif;
font-size: 12px;
}
</style>
</head>
<body>
<!-- Location for page elements. -->
<script>
// Our D3 code will go here.
var ratData = [40, 70, 60, 20, 40, 100, 60];
var w = 150;
var h = 175;
var svg = d3.select("body")
.append("svg")
.attr("height",h)
.attr("width",w);
var arrayLength = ratData.length;
var maxValue = d3.max(ratData, function(d){return +d;});
var x_axisLength = 100;
var y_axisLength = 100;
var yScale = d3.scaleLinear()
.domain([0, maxValue])
.range([0, y_axisLength]);
// select and generate rectangle elements
svg.selectAll( "rect" )
.data( ratData )
.enter()
.append("rect")
.attr( "x", function(d,i){
return i * (x_axisLength/arrayLength) + 30; // Set x coord of rect using length of array
})
.attr( "y", function(d){
return h - yScale(d) - 75; // Set y coordinate of rect using the y scale
})
.attr( "width", (x_axisLength/arrayLength) - 1) // Set bar width using length of array, leave gap of 1px between rect
.attr( "height", function(d){
return yScale(d); // Set height of using the scale
})
.attr( "fill", "steelblue");
// y-axis
svg.append("line")
.attr("x1",30)
.attr("y1",-37)
.attr("x2",30)
.attr("y2",100)
.attr("stroke-width",2)
.attr("stroke","black");
//x-axis
svg.append("line")
.attr("x1", 30)
.attr("y1", 100)
.attr("x2", 130)
.attr("y2", 100)
.attr("stroke-width", 2)
.attr("stroke", "black");
//add label
svg.append("text")
.attr("class","y label")
.attr("text-anchor","end")
.text("no. of Rats")
.attr("transform", "translate(20,20) rotate(-90)");
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment