This is just a simple graph that plots random points in the continuous range [-50, 50]. Also shows tooltips on mouseover giving the point's coordinates.
Note: In order to get even width/height, the height has been set to a value that is outside of the range of the iframe in standard mode. This may be best viewed in fullscreen or side-by-side mode.
forked from lwthatcher's block: Random Points
xxxxxxxxxx
<meta charset="utf-8">
<style> /* set the CSS */
.toolTip {
pointer-events: none;
position: absolute;
display: none;
width: 120px;
height: auto;
background: none repeat scroll 0 0 #ffffff;
padding: 9px 14px 6px 14px;
border-radius: 2px;
text-align: center;
line-height: 1.3;
color: #5B6770;
box-shadow: 0px 3px 9px rgba(0, 0, 0, .15);
}
.toolTip:after {
content: "";
width: 0;
height: 0;
border-left: 12px solid transparent;
border-right: 12px solid transparent;
border-top: 12px solid white;
position: absolute;
bottom: -10px;
left: 50%;
margin-left: -12px;
}
.toolTip span {
font-weight: 500;
color: #081F2C;
}
</style>
<body>
<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
// set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 900 - margin.left - margin.right,
height = 900 - margin.top - margin.bottom;
// set the ranges
var x = d3.scaleLinear().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var generate_random = function() {
var dataset = []
for (var i = 0; i < 20; i++) {
var x = d3.randomUniform(-50,50)();
var y = d3.randomUniform(-50,50)();
dataset.push({"x": x, "y": y});
}
return dataset
}
var tooltip = d3.select("body").append("div").attr("class", "toolTip");
// Get the data
var data = generate_random()
// format the data
data.forEach(function(d) {
d.x = +d.x;
d.y = +d.y;
});
// scale the range of the data
x.domain([-50, 50]);
y.domain([-50, 50]);
// add the dots
svg.selectAll("dot")
.data(data)
.enter().append("circle")
.attr("r", 5)
.attr("cx", function(d) { return x(d.x); })
.attr("cy", function(d) { return y(d.y); })
.on("mouseover", function(d) {
console.log(d);
tooltip
.style("opacity", 1.0)
.style("left", x(d.x) - 15 + "px")
.style("top", y(d.y) - 25 + "px")
.style("display", "inline-block")
.html("(" + d.x.toFixed(3) + ", " + d.y.toFixed(3) + ")" )
})
.on("mouseout", function(d) {
tooltip.style("opacity", 0.0);
})
// add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// add the Y Axis
svg.append("g")
.call(d3.axisLeft(y));
</script>
</body>
https://d3js.org/d3.v4.min.js