Skip to content

Instantly share code, notes, and snippets.

@larsenmtl
Created February 24, 2015 20:44
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 larsenmtl/ec50d6ab230f127d5cd9 to your computer and use it in GitHub Desktop.
Save larsenmtl/ec50d6ab230f127d5cd9 to your computer and use it in GitHub Desktop.
d3 scatterplot with tooltip mouseover
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<script>
// data that you want to plot, I've used separate arrays for x and y values
var data = [
{
x: Math.random() * 10,
y: Math.random() * 10
},
{
x: Math.random() * 10,
y: Math.random() * 10
},
{
x: Math.random() * 10,
y: Math.random() * 10
},
{
x: Math.random() * 10,
y: Math.random() * 10
}
];
xdata = [5, 10, 15, 20],
ydata = [3, 17, 4, 6];
// size and margins for the chart
var margin = {
top: 20,
right: 15,
bottom: 60,
left: 60
}, width = 500 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, 10])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, 10])
.range([height, 0]);
var tip = d3.select('body')
.append('div')
.attr('class', 'tip')
.html('I am a tooltip...')
.style('border', '1px solid steelblue')
.style('padding', '5px')
.style('position', 'absolute')
.style('display', 'none')
.on('mouseover', function(d, i) {
tip.transition().duration(0);
})
.on('mouseout', function(d, i) {
tip.style('display', 'none');
});
var chart = d3.select('body')
.append('svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'chart')
var main = chart.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'main')
// draw the x axis
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom');
main.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'main axis date')
.call(xAxis);
// draw the y axis
var yAxis = d3.svg.axis()
.scale(y)
.orient('left');
main.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'main axis date')
.call(yAxis);
// draw the graph object
var g = main.append("svg:g");
g.selectAll("scatter-dots")
.data(data)
.enter().append("svg:circle")
.attr("cy", function(d) {
return y(d.y);
})
.attr("cx", function(d, i) {
return x(d.x);
})
.attr("r", 10)
.style("opacity", 0.6)
.on('mouseover', function(d, i) {
tip.transition().duration(0);
tip.style('top', y(d.y) - 20 + 'px');
tip.style('left', x(d.x) + 'px');
tip.style('display', 'block');
})
.on('mouseout', function(d, i) {
tip.transition()
.delay(500)
.style('display', 'none');
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment