This is a follow on from the simple d3.js graph used as an example in the book D3 Tips and Tricks.
It demonstrates the loading of new data and updating a graph on a button press. It should be taken in context with the text of the book which can be downloaded for free from Leanpub.
forked from d3noob's block: Update d3.js data with button press
xxxxxxxxxx
<meta charset="utf-8">
<style> /* set the 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;
}
</style>
<body>
<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var width = 720, height= 680;
var margin = {top: 0, bottom: 270, left: 50, right: 50};
var w = width - margin.left - margin.right,
h = height - margin.top - margin.bottom;
// Set the dimensions of the canvas / graph
var svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height)
.attr('id', 'linechart');
var x_ = d3.scaleBand()
.range([0,w])
var y_ = d3.scaleLinear()
.range([h, margin.bottom])
var line = d3.line()
.x(function(d) {return x_(d.education)})
.y(function(d) {return y_(d.number)})
.curve(d3.curveStepBefore)
var xAxis = d3.axisBottom(x_);
var yAxis = d3.axisLeft(y_);
svg.append('rect')
.attr('width', 40)
.attr('height', 40)
.on('click', update);
d3.csv('data.csv', function(error, data) {
if (error) throw error;
data.forEach(function(d) {
d.number = +d.number;
d.education = d.education;
});
x_.domain(data.map(function(d) {return d.education}));
y_.domain([0,d3.max(data, function(d) {return d.number})]);
svg.append('g')
.attr('class', 'yaxis')
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.style('opacity', 1)
.call(yAxis);
svg.append('g')
.attr('class', 'xaxis')
.attr('transform', "translate(" + margin.left + "," + (h + margin.top) + ")")
.call(xAxis)
// .selectAll('text')
// .attr('transform', 'translate(0,15)rotate(-25)')
var line1 = svg.append('path')
.attr('class', 'line')
.attr('d', line(data))
.attr('transform', 'translate('+(margin.left+28.1818)+','+margin.top+')');
})
// ---- update ----
function update() {
// Get the data again
d3.csv("data-alt.csv", function(error, data) {
data.forEach(function(d) {
d.number = +d.number;
d.education = d.education;
});
// Scale the range of the data again
x_.domain(data.map(function(d) {return d.education}));
y_.domain([0,d3.max(data, function(d) {return d.number})]);
// Select the section we want to apply our changes to
//
var svg = d3.select('body')
.transition();
//
// // Make the changes
svg.select(".line")
.attr("d", line(data))
.transition()// change the line
.duration(750)
svg.select(".xaxis")
.transition()// change the x axis
.duration(750)
.call(xAxis);
svg.select(".yaxis")
.transition()// change the y axis
.duration(750)
.call(yAxis);
});
}
</script>
</body>
Modified http://d3js.org/d3.v4.min.js to a secure url
https://d3js.org/d3.v4.min.js