Skip to content

Instantly share code, notes, and snippets.

@stianSjoli
Created November 4, 2018 12:12
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 stianSjoli/3e2c8c8551cb8aa36fc2ef01017eb66f to your computer and use it in GitHub Desktop.
Save stianSjoli/3e2c8c8551cb8aa36fc2ef01017eb66f to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
</body>
<script>
var height = 500;
var width = 700;
var padding = 100;
var maxThrows = 500;
function throwDice(){
var min = 1;
var max= 7;
return Math.floor(Math.random() * (max - min) + min);
}
function createData(throws){
var data = [0];
for(var i= 0; i < maxThrows; i++) {
data.push(throwDice());
}
return data;
}
function expectations(data, throws){
var d = [0];
for(var i=2;i<throws;i++){
d.push(d3.mean(data.slice(1,i)));
}
return d;
}
var data = expectations(createData(maxThrows), maxThrows);
var xScale = d3.scaleLinear()
.domain([1,maxThrows])
.nice()
.range([padding,width - padding])
var yScale = d3.scaleLinear()
.domain([6,0])
.range([padding, height-padding])
var xAxis = d3.axisBottom(xScale)
.tickFormat(function(d){
return d;
})
var yAxis = d3.axisLeft(yScale)
.ticks(6)
var svg = d3.select("body")
.append("svg")
.attr("height", height)
.attr("width", width)
var xAxisG = svg.append("g")
.attr("transform", "translate(0" + "," + (height -padding + 2) + ")")
.call(xAxis)
xAxisG.append("text")
.attr("x", width - 100)
.attr("y", -5)
.text("antall kast")
.attr("text-anchor", "end")
.attr("font-family", "sans-serif")
.attr("font-weight", "bold")
.attr("font-size", "10px")
.attr("fill", "black");
var yAxisG = svg.append("g")
.attr("transform", "translate(95,0)")
.call(yAxis)
yAxisG.append("text")
.attr("x", 100)
.attr("y", -15)
.text("Forventning")
.attr("text-anchor", "start")
.attr("font-family", "sans-serif")
.attr("font-weight", "bold")
.attr("transform", "rotate(90)")
.attr("font-size", "10px")
.attr("fill", "black");
var line = d3.line()
.x((d) => {
return xScale(d[0]);
})
.y((d) => {
return yScale(d[1]);
});
svg.append('path')
.attr('transform', 'translate(0,0)')
.datum(data.map(function(d,i){
return [i,d];
}))
.attr('fill', 'none')
.attr('stroke', 'steelblue')
.attr('stroke-linejoin', 'round')
.attr('stroke-linecap', 'round')
.attr('stroke-width', 2.0)
.attr('d', line);
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment