simple D3 line chart
copied from: https://leanpub.com/D3-Tips-and-Tricks/read#leanpub-auto-starting-with-a-basic-graph
by ilazarte
HTML
<body><div class='main'></div></body>
CSS
body {
font: 12px Arial;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path, .axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
JavaScript
// for html <body><div class='main'></div></body>
var tooltip = d3.select("body")
.append("div")
.style("background-color", "#ffffff")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.text("a simple tooltip");
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};
var width = 600 - margin.left - margin.right;
var height = 270 - margin.top - margin.bottom;
var x = d3.scale.linear().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var valueline = d3.svg.line()
.x(function (d) {
return x(d.x);
})
.y(function (d) {
return y(d.y);
});
var svg = d3.select(".main")
.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 + ")")
.on("mouseover", function(){
var el = d3.event.fromElement;
if (!el || !el.tagName || el.tagName !== "circle") {
return;
}
var d = d3.select(el).datum();
return tooltip.style("visibility", "visible").text("x: " + d.x + " y:" + d.y.toFixed(2));
})
.on("mousemove", function(){
return tooltip.style("top", (d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");
})
.on("mouseout", function(){
var el = d3.event.fromElement;
if (!el || !el.tagName || el.tagName !== "circle") {
return;
}
return tooltip.style("visibility", "hidden");
});
// Get the data
function generateData() {
var data = [];
for (var i = 0; i < 10000; i++) {
let item = {x: i, y: Math.random()};
data.push(item);
}
return data;
}
var data = generateData();
// Scale the range of the...