I have some rookie question.
I am trying to rescale scatter plot elements (circles along with X axis) based on button click - to create 'zoom in' activity. I am lowering X axis domain for that.
It works very well with Xaxis, however its harder with circles. I must remove all of them and draw them again (the place marked in the code). This makes the process slow when lot of elements involved and also doesn't allow transition which is applied for axis scaling.
Is it possible just to change attributes of circles that i won't need to remove and redraw everything again?
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
// Define Canvas size
var width = 500;
var height = 500;
// Generate Toy Data
var randomX = d3.randomUniform(0, 880);
var randomY = d3.randomUniform(0, 800);
data_x = [];
data_y = [];
for (i = 0; i < 10000; i++) {
nume = Math.floor((Math.random() * 100));
data_x.push(nume);
data_y.push(nume);
}
// Scaling Coeffs
var coeffX = 1;
var coeffY = 1;
var coeffR = 1;
var coordX = (Math.max.apply(null, data_x)/coeffX);
var coordy = (Math.max.apply(null, data_y)/coeffY);
var x = d3.scaleLinear()
.domain([0, coordX])
.range([ 0, width]).nice();
var y = d3.scaleLinear()
.domain([0, coordy])
.range([height, 0]).nice();
var yAxis = d3.axisLeft(y).ticks(5);
var xAxis = d3.axisBottom(x).ticks(5)
//Create SVG element
var canvas = d3.select("body")
.append("svg")
.attr("width", width+50)
.attr("height", height+50)
.append("g");
// --------------- Draw Elements ---------------------
var circles = canvas.selectAll("circlepoint")
.data(data_x)
.enter()
.append("g");
circles.append("circle")
.attr("cx",function(d, i){
var tempe = data_x[i];
return x(tempe);
})
.attr("cy", function(d, i){
var tempe = data_y[i];
return y(tempe);
})
.attr("r", function(){
return 3;
})
.style("stroke", "steelblue")
.style("fill", "none")
.attr("transform", "translate(40, -20)");
var xsCont = canvas.append("g")
.attr("transform", "translate(40, " + (height-20) +")")
.attr("class","xaxis")
.call(xAxis);
var ysCont = canvas.append("g")
.attr("transform", "translate(40, -20)")
.call(yAxis);
function rescaleAxisX(tempCoeffX, tempCoeffR){
coordX = (Math.max.apply(null, data_x)/tempCoeffX);
x.domain([0, Math.max.apply(null, data_x)/tempCoeffX])
// -------- This part works well-------
canvas.select(".xaxis")
.transition().duration(750)
.call(xAxis);
// -------- End -------------
// -------- This one doesn't as expected-------
circles.remove();
circles = canvas.selectAll("circlepoint")
.data(data_x)
.enter()
.append("g");
circles.append("circle")
.attr("cx",function(d, i){
var tempe = data_x[i];
return x(tempe);
})
.attr("cy", function(d, i){
var tempe = data_y[i];
return y(tempe);
})
.attr("r", function(d, i){
return tempCoeffR;
})
.style("stroke", "steelblue")
.style("fill", "none")
.attr("transform", "translate(40, -20)");
}
// -------- End -------
// Zoom in button
var buttonZoomPlusX = d3.select("body")
.append("input")
.attr("type","button")
.attr("class","button")
.attr("value", "+")
.on("click", function(){
coeffX = coeffX + 1;
coeffR = coeffR + 1;
rescaleAxisX(coeffX, coeffR);
})
</script>
</body>
</html>
Here is implemented Fiddle
https://jsfiddle.net/sma76ntq/
Thanks a lot in advance
Well it was rookie mistake as always. Two things were missing:
1. Appending some class to circles in order not too select everything on canvas if there were more circles drawn
circles.append("circle")
.attr("cx",function(d, i){
var tempe = data_x[i];
return x(tempe);
})
.attr("cy", function(d, i){
var tempe = data_y[i];
return y(tempe);
//return y(d.y);
})
.attr("r", function(){
return 3;
})
.attr("class","eles")
.style("stroke", "steelblue")
.style("fill", "none")
.attr("transform", "translate(40, -20)");
on redrawn just select classes and change attributes.
canvas.selectAll(".eles").data(data_x)
.transition()
.duration(750)
.attr("cx",function(d, i){
var tempe = data_x[i];
return x(tempe);
})
.attr("cy", function(d, i){
var tempe = data_y[i];
return y(tempe);
});
Working Fiddle here: https://jsfiddle.net/v7q14nbm/1/
I genuinely hate to ask this question, particularly as I know it has been asked dozens of times - and I've read through the posts. But my problem remains - I simply do not understand how this mechanism works. I am new to d3js, and am using v3.x in meteor; I've gone through tutorials and have gotten something working, but can't get it to update with new data. Again, my apologies for rehashing this, but none of the other posts I've read has resolved the issue.
Here is a code fragment, I've stripped out all the stuff that shouldn't make a difference to focus on the core functionality:
var w = 800;
var h = 800;
var intensity = 25;
var margin = {
top: 75,
right: 100,
bottom: 75,
left: 60
};
var svg = d3.select('#heatmap')
.append('svg')
.attr('width', w + margin.left + margin.right)
.attr('height', h + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// get csv data, x & y coords, etc...
createHeatmap = function(csv, x, y) {
var data = d3.csv.parseRows(csv).map(function(row) {
return row.map(function(d) {
return +d;
});
});
// set some values
var min = 0;
var max = d3.max(data, function(d, i) {
return i + 1;
});
var rectSize = 4;
// set the scales for both axes
...
// set up the axes
...
// define colorScale
...
// create heatmap
svg.selectAll('g')
.data(data)
.enter()
.append('g')
.selectAll('rect')
.data(function(d, i, j) {
return d;
})
.enter() // start drawing rects
.append('rect')
.attr('x', function(d, i, j) {
return (i * rectSize);
})
.attr('y', function(d, i, j) {
return (j * rectSize);
})
.attr('width', w / max)
.attr('height', h / max)
.style('fill', function(d, i, j) {
return colorScale(d * intensity);
});
// append axes, scales, labels, etc.
}
// create heatmap
createHeatmap(csv, x, y);
My problem is that I do not understand why the chart doesn't update the heatmap when I pass new data into createHeatmap().
I stepped through it in the debugger and everything works as I would expect during the initial creation of the heatmap, which renders correctly. When I send new data is when the mystery starts. The debugger shows, deep within d3js itself (not in my code) that the enter() has an array full od null values instead of the data I am passing in. The data exists up until that point. So, as d3js processes the null data it naturally returns an empty object so no update occurs.
Obviously I am not doing the update correctly but am clueless about what I need to do to correct it.
Any advise is greatly appreciated.
Thx!
Update:
Andrew, thanks for the response. I tried your first suggestion, modifying your example to fit my data, but it doesn't update with new data.
My changes:
var w = 800;
var h = 800;
var intensity = 25;
var margin = {
top: 75,
right: 100,
bottom: 75,
left: 60
};
var svg = d3.select('#heatmap')
.append('svg')
.attr('width', w + margin.left + margin.right)
.attr('height', h + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// get csv data, x & y coords, etc...
createHeatmap = function(csv, x, y) {
var data = d3.csv.parseRows(csv).map(function(row) {
return row.map(function(d) {
return +d;
});
});
// set some values
var min = 0;
var max = d3.max(data, function(d, i) {
return i + 1;
});
var rectSize = 4;
// set the scales for both axes
...
// set up the axes
...
// define colorScale
...
// append group of svg elements bound to data
var rows = svg.selectAll('g')
.data(data);
// enter new rows where needed
rows.enter().append('g');
// select all rects
var rects = rows.selectAll('rect')
.data(function(d, i, j) {
return d;
});
// enter new rects:
rects.enter().append('rect')
.attr('x', function(d, i, j) {
return (i * rectSize);
})
.attr('y', function(d, i, j) {
return (j * rectSize);
})
.attr('width', w / max)
.attr('height', h / max)
.style('fill', function(d, i, j) {
return colorScale(d * intensity);
});
Added snippet:
var csv = "'3, 6, 0, 8'\n'1, 9, 0, 4'\n'3, 0, 1, 8'\n'4, 0, 2, 7";
csv = csv.replace(/'/g,'');
var button = d3.select('button')
.on('click', function() {
createHeatmap(update());
});
var w = 120;
var h = 120;
var intensity = 10;
var margin = {
top: 25,
right: 25,
bottom: 25,
left: 25
};
var svg = d3.select('#heatmap')
.append('svg')
.attr('width', w + margin.left + margin.right)
.attr('height', h + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
createHeatmap(csv);
function createHeatmap(csv) {
console.log(csv);
var data = d3.csv.parseRows(csv).map(function(row) {
return row.map(function(d) {
return +d;
});
});
var min = 0;
var max = d3.max(data, function(d, i) {
return i + 1;
});
var rectSize = 30;
// define a colorScale with domain and color range
var colorScale = d3.scale.linear()
.domain([0,0.5,1])
.range(['red', 'green', 'blue']);
// append group of svg elements bound to data
var rows = svg.selectAll('g')
.data(data);
// enter new rows where needed
rows.enter().append('g');
// select all rects
var rects = rows.selectAll('rect')
.data(function(d, i, j) {
return d;
});
// enter new rects:
rects.enter().append('rect')
.attr('x', function(d, i, j) {
return (i * rectSize);
})
.attr('y', function(d, i, j) {
return (j * rectSize);
})
.attr('width', w / max)
.attr('height', h / max)
.style('fill', function(d, i, j) {
return colorScale(d * intensity);
});
}
function update() {
var data = "'0, 1, 9, 5'\n'4, 0, 7, 2'\n'6, 3, 0, 8'\n'5, 3, 7, 0";
data = data.replace(/'/g,'');
return data;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<button>Update</button>
<div id="heatmap"></div>
The issue is in your method chaining.
On first run, things should run as expected:
// create heatmap
svg.selectAll('g') // 1. select all g elements
.data(data) // 2. assign data
.enter() // 3. enter and append a g for each item in the data array
.append('g') // that doesn't have a corresponding element in the DOM (or more accurately, the selection)
.selectAll('rect') // 4. For each newly entered g, select child rectangles
.data(function(d, i, j) { // 5. assign data to child selection.
return d;
})
.enter() // 6. Enter and append a rect for each item in the child g's data array
.append("rect") // that doesn't have a corresponding element in the DOM.
.... // 7. Style
On that first run, we select all the gs, there are none, so the enter selection will have an element for each item in the data array: we are entering everything. Same as with the child rectangles: there are no child rectangles existing when you make the selection, so you enter everything in the child data array.
On the second run, with svg.selectAll("g"), you select all the gs you created the first time around - there is no need to enter anything if the data array has the same number of items. You don't want to append anything: enter().append() the second time (not that you are appending more elements with .append() in any event).
Essentially on the second pass you are modifying an empty selection.
Instead you want to update. While the enter selection is empty on the second pass, the update selection has all the existing gs.
There are a few methods to do this, one is to break your chaining:
This is a version 3 solution:
var rows = svg.selectAll("g")
.data(data);
// enter new rows where needed
rows.enter().append("g")
// Select all rects
var rects = rows.selectAll("rect")
.data(function(d) { return d; })
// Enter new rects:
rects.enter().append("rect")
// Update rects (all rects, not just the newly entered):
rects.attr()...
The below snippet uses this pattern, it enters new rects and gs as needed. And then updates all the rects and gs afterwards. This takes advantage of a magic in d3v3, where the update selection and the enter selection are merged internally, this is not the case in d3v4,v5, which I'll show below.
var button = d3.select("button")
.on("click", function() {
update(random());
})
var svg = d3.select("div")
.append("svg");
var color = d3.scale.linear()
.domain([0,0.5,1])
.range(["red","orange","yellow"])
update(random());
function update(data) {
var rows = svg.selectAll("g")
.data(data);
// enter new rows where needed
rows.enter()
.append("g")
.attr("transform", function(d,i) {
return "translate("+[0,i*22]+")";
})
// Select all rects:
var rects = rows.selectAll("rect")
.data(function(d) { return d; })
// Enter new rects:
rects.enter().append("rect")
// Update rects:
rects.attr("fill", function(d) {
return color(d);
})
.attr("x", function(d,i) { return i*22; })
.attr("width", 20)
.attr("height", 20);
console.log("entered rows:" + rows.enter().size());
console.log("entered rects:" + rects.enter().size());
}
function random() {
return d3.range(5).map(function() {
return d3.range(5).map(function() {
return Math.random();
})
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<button>Update</button>
<div></div>
v4/v5:
For v4/v5, which I suggest upgrading to, the pattern is a bit different as you have to explicitly merge the enter and update selections:
var button = d3.select("button")
.on("click", function() {
update(random());
})
var svg = d3.select("div")
.append("svg");
var color = d3.scaleLinear()
.domain([0,0.5,1])
.range(["red","orange","yellow"])
update(random());
function update(data) {
var rows = svg.selectAll("g")
.data(data);
// enter new rows where needed
rows = rows.enter()
.append("g")
.merge(rows) // merge with existing rows
.attr("transform", function(d,i) {
return "translate("+[0,i*22]+")";
})
// Select all rects:
var rects = rows.selectAll("rect")
.data(function(d) { return d; })
// Enter new rects:
rects = rects.enter().append("rect")
.merge(rects);
// Update rects:
rects.attr("fill", function(d) {
return color(d);
})
.attr("x", function(d,i) { return i*22; })
.attr("width", 20)
.attr("height", 20);
}
function random() {
return d3.range(5).map(function() {
return d3.range(5).map(function() {
return Math.random();
})
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<button>Update</button>
<div></div>
Update
Your snippet almost incorporates the changes, but you still need to break up the second selection, that of the rectangles, so that you enter new rectangles and then update all of them:
var csv = "'3, 6, 0, 8'\n'1, 9, 0, 4'\n'3, 0, 1, 8'\n'4, 0, 2, 7";
csv = csv.replace(/'/g,'');
var button = d3.select('button')
.on('click', function() {
createHeatmap(update());
});
var w = 120;
var h = 120;
var intensity = 10;
var margin = {
top: 25,
right: 25,
bottom: 25,
left: 25
};
var svg = d3.select('#heatmap')
.append('svg')
.attr('width', w + margin.left + margin.right)
.attr('height', h + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
createHeatmap(csv);
function createHeatmap(csv) {
console.log(csv);
var data = d3.csv.parseRows(csv).map(function(row) {
return row.map(function(d) {
return +d;
});
});
var min = 0;
var max = d3.max(data, function(d, i) {
return i + 1;
});
var rectSize = 30;
// define a colorScale with domain and color range
var colorScale = d3.scale.linear()
.domain([0,0.5,1])
.range(['red', 'green', 'blue']);
// append group of svg elements bound to data
var rows = svg.selectAll('g')
.data(data);
// enter new rows where needed
rows.enter().append('g');
// select all rects
var rects = rows.selectAll('rect')
.data(function(d, i, j) {
return d;
});
// enter new rects:
rects.enter().append('rect');
// CHANGES HERE:
// Broke chain so that update actions aren't carried out on the enter selection:
rects.attr('x', function(d, i, j) {
return (i * rectSize);
})
.attr('y', function(d, i, j) {
return (j * rectSize);
})
.attr('width', w / max)
.attr('height', h / max)
.style('fill', function(d, i, j) {
return colorScale(d * intensity);
});
}
function update() {
var data = "'0, 1, 9, 5'\n'4, 0, 7, 2'\n'6, 3, 0, 8'\n'5, 3, 7, 0";
data = data.replace(/'/g,'');
return data;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<button>Update</button>
<div id="heatmap"></div>
I have a simple D3 simulation that looks like this
When I click the 'remove 1 and 4' button I want to remove nodes 1 and 4 from the simulation. The result, however, is the following:
Visually it seems to have removed 3 and 4 (not 1 and 4).
My code is below. Any ideas what I need to do to make this work correctly?
I'm assuming I've fundamentally misunderstood how updating nodes works in d3. Any help appreciated.
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<!DOCTYPE html>
<meta charset="utf-8">
<script type="text/javascript" src="http://d3js.org/d3.v3.js"></script>
<body>
<button>remove 1 and 4</button>
<script>
var width = 400,
height = 400;
var nodes = [1, 2, 3, 4].map(function(x) { return { name: x}});
var force = d3.layout.force()
.size([width, height])
.nodes(nodes)
.linkDistance(30)
.charge(-500)
.on("tick", tick);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var content = svg.append("g");
var nodesData = force.nodes(),
nodeElement = content.selectAll(".node");
function tick() {
nodeElement.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
}
d3.selectAll('button').on('click', function() {
//remove 1 and 4
nodesData = [
nodesData[1],
nodesData[2]
]
refresh();
});
var WIDTH = 100;
//
// this logic is slightly modified from http://bl.ocks.org/tgk/6068367
//
function refresh() {
force.nodes(nodesData)
nodeElement = nodeElement.data(nodesData);
var nodeGroup = nodeElement.enter()
.append('g')
.attr("class", "node");
// node text
nodeGroup.append("text")
.attr("class", "nodetext")
.attr("dx", WIDTH/2)
.attr("dy", "14px")
.text(function(n) { return 'node '+n.name })
nodeElement.exit().remove();
force.start();
}
refresh();
</script>
You can solve your problem by adding a "key" function to the .data call inside the refresh function: nodeElement = nodeElement.data(nodesData, function(d){ return d.name });.
The problem you saw is not specific to updating nodes. Ordinarily, selections work based off of index of the data array. So if first D3 had [a,b,c,d] and now it has [a,d], it's going to take the first two elements ([a,b]) unless you tell it the key that defines each item in the array. That's what the function above does.
For more see https://github.com/d3/d3-selection/blob/master/README.md#selection_data
Not sure if this is a plnkr issue or an issue with my code.. although the console is not showing any errors.
I am writting a little svg script and it does not render.
var w = 300;
var h = 100;
var padding = 2;
var dataset = [5, 10, 14, 20, 25];
var svg = d3.select("body").append("svg").attr("width", w).attr("height", h);
svg.selectAll('rect')
.data(dataset)
.enter()
.append('rect')
.attr('x', function(d, i) {
return i * (w/dataset.length);
})
.attr('y', function(d) {
return h - (d);
})
.attr("width", w/ dataset.length - padding)
.attr("height", function(d) {
return d;
});
Plnkr here:
http://plnkr.co/edit/X7KomlmOVS6C0zhNL19b
Run it inside a document.ready or wait till the window is loaded. http://plnkr.co/edit/TmFWndyCgLk7GYEng7XP
<!DOCTYPE html>
<html>
<head>
<script data-require="d3#*" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
</body>
</html>
and in the JS
$(document).ready(function(){
var w = 300;
var h = 100;
var padding = 2;
var dataset = [5, 10, 14, 20, 25];
var svg = d3.select("body").append("svg").attr("width", w).attr("height", h);
console.log('running the plnkr');
svg.selectAll('rect')
.data(dataset)
.enter()
.append('rect')
.attr('x', function(d, i) {
return i * (w/dataset.length);
})
.attr('y', function(d) {
return h - (d * 4);
})
.attr("width", w/ dataset.length - padding)
.attr("height", function(d) {
return d * 4;
});
});
I have simple code here from Interactive Data Visualization by Scott Murray with minor changes. What I changed is the initial data's length 5 is different from the dataset1's length 25 in the click function.
However, every time I click and update, it does generate random new numbers but the length only shows 5 bars.
What is the reason for this? And how could I modify to change it?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="../d3/d3.v3.js"></script>
<title>D3 index01 </title>
<style type="text/css">
div.bar{
display: inline-block;
width: 20px;
height: 75px;
background-color: teal;
margin-right: 2px;
}
</style>
</head>
<body>
<p> click it </p>
<script type = "text/javascript">
var w=600;
var h = 250;
var dataset = [5,10,13,14,15];
var xScale = d3.scale.ordinal()
.domain(d3.range(dataset.length)).rangeRoundBands([0,w],0.05);
var yScale = d3.scale.linear()
.domain([0,d3.max(dataset)]).range([0,h]);
var svg = d3.select("body")
.append("svg")
.attr("width",w)
.attr("height",h);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d,i){
return xScale(i);
})
.attr("y",function(d){return (h-yScale(d));})
.attr("width",xScale.rangeBand())
.attr("height",function(d){return yScale(d);});
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i)+xScale.rangeBand() / 2;
})
.attr("y", function(d) {
return h - yScale(d) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
d3.select("p")
.on("click",function(){
var dataset1 = [];
for(var i=0; i<25; i++){
var newNumber = Math.floor(Math.random()*25);
dataset1.push(newNumber);
}
svg.selectAll("rect").data(dataset1)
.transition()
.delay(function(d,i){
return i*100;
})
.duration(500)
.attr("x",function(d,i){
return xScale(i);
})
.attr("y",function(d){
return h-yScale(d);
})
.attr("x", function(d,i){
return xScale(i);
})
.attr("height",function(d){
return yScale(d);
})
.attr("fill",function(d){
return "rgb(0,0, " + (d*10) + ")";
});
svg.selectAll("text").data(dataset1).
text(function(d) {
return d;
})
.attr("x", function(d, i) {
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
return h - yScale(d) + 14;
});
});
</script>
</body>
</html>
The issue, as I see it, is that when you update the rects with the new numbers using this statement
svg.selectAll("rect").data(dataset1)
the selectAll only selects the original 5 rects that were created based on dataset
var dataset = [5,10,13,14,15];
You could either create them all from the start with an equally sized starting dataset or append new rect svgs at this point.
Since you are doing a transition on the original rects I think it makes the most sense to just start with all 25. You could write a function to automatically generate this and put it where dataset is defined:
var dataset = [];
var numBars = 25; // This is the number of bars you want
var maxHeight = 25; // Seems like this is independent and needed as a ceiling
for(var i =0;i < N;i++){
var newNumber = Math.floor(Math.random()* maxHeight);
dataset.push(newNumber);
}
You could then replace 25 with numBars within your onclick function as well.