Incorrect SVG group being deleted - javascript

I want to remove the bar that is clicked, but for some reason it is always removing the last bar instead. I think the answer may be in the following article (http://pothibo.com/2013/09/d3-js-how-to-handle-dynamic-json-data/), but I'm not sure if manually assigning a key to each element is necessary. I have spent hours trying to get this to work, so I'm hoping someone can point me in the right direction. Thanks in advance.
<html>
<head>
<title>Interactive Div-based Bar Chart</title>
<style type="text/css">
.chart rect {
fill: teal;
}
.chart text {
fill: white;
font: 30px sans-serif;
text-anchor: end;
}
</style>
<script src="Scripts/d3.min.js"></script>
</head>
<body>
<div id="data-field"></div>
<button id="add-btn">Add Data</button>
<p>Click on a bar to remove it</p>
<script>
var barHeight = 75, margin = 3, padding = 3;
var chartData = [6,12,15,21,29,41];
var chart = d3.select("body").append("svg").attr("class","chart");
drawChart();
function drawChart() {
var selection = chart.selectAll("g")
.data(chartData);
// Remove extra bars
selection.exit()
.remove();
// Add more bars
var groups = selection.enter()
.append("g");
var bars = groups
.append("rect");
var labels = groups
.append("text");
// Update existing bars
groups
.attr("transform", function (d, i) { return "translate(0," + i * (barHeight + margin) + ")"; })
.on("click", function (d, i) { chartData.splice(i, 1); drawChart(); });
bars
.attr("width", function (d) { return d * 10 + "px"; })
.attr("height", barHeight);
labels
.attr("x", function (d) { return d * 10 - padding + "px"; })
.attr("y", barHeight / 3 + padding + "px")
.text(function (d) { return d; });
// update list of numbers
d3.select("#data-field").text("numbers: [" + chartData.join(", ") + "]");
}
// add more data
d3.select("#add-btn")
.on("click", function(d) { chartData.push(Math.round(Math.random() * 100)); drawChart(); });
</script>
</body>
</html>

Check my solution here: http://fiddle.jshell.net/sydvpsfp/
Major problem was that you were not deleting all the old bars at the begining of drawChart function.
I had added this:
// remove any old bars
var oldBars=chart.selectAll("g");
if (oldBars.size()>0)
oldBars.remove();

Here are the changes you need to make, with comments:
// Update existing bars; do not use groups here since it represents
// only the ENTER selection, and not ALL g elements
selection
.attr("transform", function (d, i) { return "translate(0," + i * (barHeight + margin) + ")"; })
.on("click", function (d, i) {
d3.select(this).remove(); // remove appropriate DOM element
chartData.splice(i, 1);
drawChart();
});
And here is the FIDDLE.
IMPORTANT EDIT:
After #loucatsfan asked me why not simply getting rid of selection.exit().remove(); since it made no difference, I realized the importance of making my answer more idiomatic. So, I created an updated fiddle that leverages the exit selection and removes the need to manually delete the DOM element.
Also, and just as important, there are some subtle differences between handling updates for grouped vs. non-grouped elements (use of select vs. selectAll). So, I revised the code to more appropriately handle grouped elements.
You can find more info on the proper handling of grouped elements here and here. But here is the promised improvement:
UPDATED FIDDLE.

Related

Append two elements in svg at the same level

I'm using d3.js
Hi, I'm having an issue finding how to append two elements (path and image) to the same g (inside my svg) from the same data. I know how to do this, but the tricky thing is I need to get the BBox values of the "path" elements in order to place the "image" elements in the middle... My goal is actually to place little clouds in the center of cities on a map like this : this is the map I am trying to reproduce
On the map it's not centered but I have to do so. So this is my current code:
// Draw the map
svg.append("g")
.selectAll("path")
.data(mapEPCI.features)
.enter()
.append("path")
.attr("fill", d => d.properties.color)
.attr("d", d3.geoPath().projection(projection))
.style("stroke", "white")
.append("image")
.attr("xlink:href", function(d) {
if (d.properties.plan_air == 1)
return ("data/page8_territoires/cloud.png")
else if (d.properties.plan_air == 2)
return ("data/page8_territoires/cloudgray.png")
})
.attr("width", "20")
.attr("height", "15")
.attr("x", function (d) {
let bbox = d3.select(this.parentNode).node().getBBox();
return bbox.x + 30})
.attr("y", function (d) {
return d3.select(this.parentNode).node().getBBox().y + 30})
This gets the right coordinates for my images but it's because the parent node is actually the path... If I append the image to the g element, is there a way to get the "BrotherNode", or maybe the last child of the "g" element ? I don't know if I'm clear enough but I hope you get my point.
I'm kinda new to js so maybe I'm missing something simple I just don't know yet
Thanks for your help
I would handle your data at the g level and create a group for every map feature (country) which contains the path and a sibling image:
<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<svg width="600" height="600"></svg>
<script>
let svg = d3.select('svg'),
mapEPCI = {
features: [100, 200, 300, 400]
};
let g = svg.selectAll('g')
.data(mapEPCI.features)
// enter selection is collection of g
let ge = g.enter().append("g");
// append a path to each g according to data
ge.append('path')
.attr("d", (d) => "M" + d + ",10L" + d + ",100")
.style("stroke", "black");
// append a sibling image
ge.append("image")
.attr("xlink:href", "https://placeimg.com/20/15/animals")
.attr("width", "20")
.attr("height", "15")
.attr("transform", function(d) {
// find my sibling path to get bbox
let sibling = this.parentNode.firstChild;
let bbox = sibling.getBBox();
return "translate(" + (bbox.x - 20 / 2) + "," + (bbox.y + bbox.height / 2 - 15 / 2) + ")"
});
</script>
</body>
</html>

d3 filtering function not working based on attribute

Hey so I cannot seem to figure out this issue. Basically my goal for this predicament is when the item is dragged over the div element I want it to return the element that closely responds with the div element.
I set attributes to the div element in correspondence with its coordinates like so.
chars = grid
.selectAll("svg")
.data(data.nodes)
.enter()
.append("div")
.attr("class", "gridData")
.attr("gridX", function(d) {return d.x})
.attr("gridY", function(d) {return d.y})
.on('contextmenu', function () {
d3.event.preventDefault()
}).call(drag);
When I use the drag end function I want to grasp the element that corresponds with the coordinates like so.
drag.on('dragend', function(d) {
var hx = helper.datum().x;
var hy = helper.datum().y;
d.x = hx;
d.y = hy;
d3.select(this).transition().duration(100).style('left', d.x + 'px').style('top', d.y + 'px')
.each('end', function () {
helper.remove();
});
if (d.sample === "sample1") {
var selection = d3.selectAll(".gridData").filter("gridX", d.x);
console.log(selection);
d3.select(this).remove();
}
});
Except my filter function is empty. I cannot figure out why the filter function is empty. The selection all returns an Array of 20 containers that has all the corresponding x and y coordinates. So I figured it should return.

selectAll("rect") selects all rectangles, but doesn't apply the mouseover function to some

Working through the excellent Interactive Data Visualization for the Web book and have created (a monstrosity of a) script to create an interactive bar chart that:
Adds a new bar to the end when clicking on the svg element
Generates a new set of 50 bars when clicking on the p element
I have added a mouseover event listener to change the color of the bars when hovering over. The problem is that bars added via 1. above are not changing color. As far as I can tell, the bars are getting selected properly, but for whatever reason, the mouseover event is never being fired for these bars:
svg.select(".bars").selectAll("rect")
.on("mouseover", function() {
d3.select(this)
.transition()
.attr("fill", "red");
})
Thanks in advance for your help, it is always greatly appreciated.
Here is the full code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Interactive Data Visualization for the Web Program-Along</title>
<style>
/* axes are made up of path, line, and text elements */
.axis path,
.axis line {
fill: none;
stroke: navy;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
/* color is CSS property, but need SVG property fill to change color */
fill: navy;
}
</style>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<p>Click on this text to update the chart with new data values.</p>
<script type="text/javascript">
var n = 50;
var domain = Math.random() * 1000;
function gen_data(n, domain) {
var d = [];
for (var i = 0; i < n; i++) {
d.push(
{ id: i, val: Math.random() * domain }
);
}
return d;
}
// define key function once for use in .data calls
var key = function(d) {
return d.id;
};
var dataset = gen_data(n, domain);
// define graphic dimensions
var w = 500, h = 250, pad = 30;
// get input domains
var ylim = d3.extent(dataset, function(d) {
return d.val;
});
// define scales
var x_scale = d3.scale.ordinal()
.domain(d3.range(dataset.length))
.rangeRoundBands([0, w - pad], 0.15);
var y_scale = d3.scale.linear()
.domain([ylim[0], ylim[1] + pad]) // could have ylim[0] instead
// range must be backward [upper, lower] to accommodate svg y inversion
.range([h, 0]); // tolerance to avoid clipping points
var color_scale = d3.scale.linear()
.domain([ylim[0], ylim[1]])
.range([0, 255]);
// create graphic
var svg = d3.select("body").append("div").append("svg")
.attr("width", w)
.attr("height", h);
svg.append("g")
.attr("class", "bars")
.selectAll(".bars rect")
.data(dataset)
.enter()
.append("rect")
.attr({
x: function(d, i) {
return x_scale(i) + pad;
},
y: function(d) {
return y_scale(d.val);
},
width: x_scale.rangeBand(), // calculates width automatically
height: function(d) { return h - y_scale(d.val); },
opacity: 0.6,
fill: function(d) {
return "rgb(50, 0, " + Math.floor(color_scale(d.val)) + ")";
}
});
// add axes
var yAxis = d3.svg.axis()
.scale(y_scale) // must be passed data-to-pixel mapping (scale)
.ticks(3) // optional (d3 can assign ticks automatically)
.orient("left");
// since function, must be called
// create <g> to keep things tidy, to style via CSS, & to adjust placement
svg.append("g")
.attr({
class: "axis",
transform: "translate(" + pad + ",0)"
})
.call(yAxis);
// add event listener for clearing/adding all new values
d3.select("p")
.on("click", function() {
// generate new dataset
dataset = gen_data(n, domain);
// remove extra bars
d3.selectAll(".bars rect")
.data(dataset, function(d, i) { if (i < 50) { return d; }})
.exit()
.transition()
.attr("opacity", 0)
.remove();
// update scales
x_scale.domain(d3.range(dataset.length))
.rangeRoundBands([0, w - pad], 0.15);
ylim = d3.extent(dataset, function(d) {
return d.val;
});
y_scale.domain([ylim[0], ylim[1] + pad]);
// update bar values & colors
d3.selectAll(".bars rect")
.data(dataset)
.transition()
.duration(500)
.attr("x", function(d, i) { return x_scale(i) + pad; })
.transition() // yes, it's really this easy...feels like cheating
.delay(function(d, i) { return i * (1000 / dataset.length); }) // set dynamically
.duration(1000) // optional: control transition duration in ms
.each("start", function() {
// "start" results in immediate effect (no nesting transitions)
d3.select(this) // this to select each element (ie, rect)
.attr("fill", "magenta")
.attr("opacity", 0.2);
})
.attr({
y: function(d) { return y_scale(d.val); },
height: function(d) { return h - y_scale(d.val); }
})
.each("end", function() {
d3.selectAll(".bars rect")
.transition()
// needs delay or may interrupt previous transition
.delay(700)
.attr("fill", function(d) {
return "rgb(50, 0, " + Math.floor(color_scale(d.val)) + ")";
})
.attr("opacity", 0.6)
.transition()
.duration(100)
.attr("fill", "red")
.transition()
.duration(100)
.attr("fill", function(d) {
return "rgb(50, 0, " + Math.floor(color_scale(d.val)) + ")";
});
});
// update axis (no need to update axis-generator function)
svg.select(".axis")
.transition()
.duration(1000)
.call(yAxis);
});
// extend dataset by 1 for each click on svg
svg.on("click", function() {
// extend dataset & update x scale
dataset.push({ id: dataset.length, val: Math.random() * domain });
x_scale.domain(d3.range(dataset.length));
// add this datum to the bars <g> tag as a rect
var bars = svg.select(".bars")
.selectAll("rect")
.data(dataset, key);
bars.enter() // adds new data point(s)
.append("rect")
.attr({
x: w,
y: function(d) {
return y_scale(d.val);
},
width: x_scale.rangeBand(), // calculates width automatically
height: function(d) { return h - y_scale(d.val); },
opacity: 0.6,
fill: function(d) {
return "rgb(50, 0, " + Math.floor(color_scale(d.val)) + ")";
}
});
// how does this move all the other bars!?
// because the entire dataset is mapped to bars
bars.transition()
.duration(500)
.attr("x", function(d, i) {
return x_scale(i) + pad;
});
});
// add mouseover color change transition using d3 (vs CSS)
svg.select(".bars").selectAll("rect")
.on("mouseover", function() {
d3.select(this)
.transition()
.attr("fill", "red");
})
.on("mouseout", function(d) {
d3.select(this)
.transition()
.attr("fill", function() {
return "rgb(50, 0, " + Math.floor(color_scale(d.val)) + ")";
})
.attr("opacity", 0.6);
})
// print to console when clicking on bar = good for debugging
.on("click", function(d) { console.log(d); });
</script>
</body>
</html>
UPDATE:
Thanks to Miroslav's suggestion, I started playing around with different ways to resolve the issue and came across Makyen's answer to this related SO post.
While I imagine there is a more performant way to handle this, I have decided to rebind the mouseover event listener each time the mouse enters the svg element using the following code:
svg.on("mouseover", mouse_over_highlight);
// add mouseover color change transition using d3 (vs CSS)
function mouse_over_highlight() {
d3.selectAll("rect")
.on("mouseover", function () {
d3.select(this)
.transition()
.attr("fill", "red");
})
.on("mouseout", function (d) {
d3.select(this)
.transition()
.attr("fill", function () {
return "rgb(50, 0, " + Math.floor(color_scale(d.val)) + ")";
})
.attr("opacity", 0.6);
})
// print to console when clicking on bar = good for debugging
.on("click", function (d) {
console.log(d);
});
}
Reason your event fires only for first bar and not the dynamic ones is because of the way you added your event listener.
Your way only puts events on elements already present on the page (they are in DOM structure). Any new elements will not have this event listener tied to them.
You can make a quick check for this by putting your code in function like
function setListeners() {
svg.select(".bars").selectAll("rect").on("mouseover", function() {
d3.select(this)
.transition()
.attr("fill", "red");
})
}
After you add any new bars on the screen, add this function call and see if it works for all elements. If this is indeed the case, you need to write your event listener in a way it works for all elements, including dynamically added ones. The way to do that is to set the event to some of the parent DOM nodes and then checking if you are hovering on exactly the thing you want the event to fire.
Example:
$(document).on(EVENT, SELECTOR, function(){
code;
});
This will put the event on the body and you can check then selector after it's triggered if you are over correct element. However it was a while since I worked with D3 and I'm not sure how D3, SVG and jQuery play together, last time I was doing it they had some troubles.
In this case event should be mouseover, selector should be your rect bars and function should be what ever you want to run.
If everything else fails in case they won't cooperate, just use the function to set event listeners and call it every time after you dynamically add new elements.

d3 is not defined - ReferenceError

I am trying to use a "fancy graph" found at http://bl.ocks.org/kerryrodden/7090426:
The way I've done it was to download the code and simply edit the CSV file to match my data. Then I simply open the .html-file in Firefox to see the interactive graph. However, using it at a another computer I get the following errors:
ReferenceError: d3 is not defined sequences.js:25
ReferenceError: d3 is not defined index.html:28
As I have almost no knowledge of d3 or javascript I am a bit lost.
Can any of you give me a hint to what is causing the errors and how I should correct the code?
I've done a single alteration to the code making it the following:
Javascript:
// Dimensions of sunburst.
var width = 750;
var height = 600;
var radius = Math.min(width, height) / 2;
// Breadcrumb dimensions: width, height, spacing, width of tip/tail.
var b = {
w: 75, h: 30, s: 3, t: 10
};
// Mapping of step names to colors.
var colors = {
"G0": "#5687d1",
"G1": "#5c7b61",
"G2": "#de783b",
"G3": "#6ab975",
"G4": "#a173d1",
"G5": "#72d1a1",
"Afgang": "#615c7b"
};
// Total size of all segments; we set this later, after loading the data.
var totalSize = 0;
var vis = d3.select("#chart").append("svg:svg")
.attr("width", width)
.attr("height", height)
.append("svg:g")
.attr("id", "container")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var partition = d3.layout.partition()
.size([2 * Math.PI, radius * radius])
.value(function(d) { return d.size; });
var arc = d3.svg.arc()
.startAngle(function(d) { return d.x; })
.endAngle(function(d) { return d.x + d.dx; })
.innerRadius(function(d) { return Math.sqrt(d.y); })
.outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });
// Use d3.text and d3.csv.parseRows so that we do not need to have a header
// row, and can receive the csv as an array of arrays.
d3.text("sequences.csv", function(text) {
var csv = d3.csv.parseRows(text);
var json = buildHierarchy(csv);
createVisualization(json);
});
// Main function to draw and set up the visualization, once we have the data.
function createVisualization(json) {
// Basic setup of page elements.
initializeBreadcrumbTrail();
drawLegend();
d3.select("#togglelegend").on("click", toggleLegend);
// Bounding circle underneath the sunburst, to make it easier to detect
// when the mouse leaves the parent g.
vis.append("svg:circle")
.attr("r", radius)
.style("opacity", 0);
// For efficiency, filter nodes to keep only those large enough to see.
var nodes = partition.nodes(json)
.filter(function(d) {
return (d.dx > 0.005); // 0.005 radians = 0.29 degrees
});
nodes = nodes.filter(function(d) {
return (d.name != "end"); // BJF: Do not show the "end" markings.
});
var path = vis.data([json]).selectAll("path")
.data(nodes)
.enter().append("svg:path")
.attr("display", function(d) { return d.depth ? null : "none"; })
.attr("d", arc)
.attr("fill-rule", "evenodd")
.style("fill", function(d) { return colors[d.name]; })
.style("opacity", 1)
.on("mouseover", mouseover);
// Add the mouseleave handler to the bounding circle.
d3.select("#container").on("mouseleave", mouseleave);
// Get total size of the tree = value of root node from partition.
totalSize = path.node().__data__.value;
};
// Fade all but the current sequence, and show it in the breadcrumb trail.
function mouseover(d) {
var percentage = (100 * d.value / totalSize).toPrecision(3);
var percentageString = percentage + "%";
if (percentage < 0.1) {
percentageString = "< 0.1%";
}
d3.select("#percentage")
.text(percentageString);
d3.select("#explanation")
.style("visibility", "");
var sequenceArray = getAncestors(d);
updateBreadcrumbs(sequenceArray, percentageString);
// Fade all the segments.
d3.selectAll("path")
.style("opacity", 0.3);
// Then highlight only those that are an ancestor of the current segment.
vis.selectAll("path")
.filter(function(node) {
return (sequenceArray.indexOf(node) >= 0);
})
.style("opacity", 1);
}
// Restore everything to full opacity when moving off the visualization.
function mouseleave(d) {
// Hide the breadcrumb trail
d3.select("#trail")
.style("visibility", "hidden");
// Deactivate all segments during transition.
d3.selectAll("path").on("mouseover", null);
// Transition each segment to full opacity and then reactivate it.
d3.selectAll("path")
.transition()
.duration(1000)
.style("opacity", 1)
.each("end", function() {
d3.select(this).on("mouseover", mouseover);
});
d3.select("#explanation")
.transition()
.duration(1000)
.style("visibility", "hidden");
}
// Given a node in a partition layout, return an array of all of its ancestor
// nodes, highest first, but excluding the root.
function getAncestors(node) {
var path = [];
var current = node;
while (current.parent) {
path.unshift(current);
current = current.parent;
}
return path;
}
function initializeBreadcrumbTrail() {
// Add the svg area.
var trail = d3.select("#sequence").append("svg:svg")
.attr("width", width)
.attr("height", 50)
.attr("id", "trail");
// Add the label at the end, for the percentage.
trail.append("svg:text")
.attr("id", "endlabel")
.style("fill", "#000");
}
// Generate a string that describes the points of a breadcrumb polygon.
function breadcrumbPoints(d, i) {
var points = [];
points.push("0,0");
points.push(b.w + ",0");
points.push(b.w + b.t + "," + (b.h / 2));
points.push(b.w + "," + b.h);
points.push("0," + b.h);
if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.
points.push(b.t + "," + (b.h / 2));
}
return points.join(" ");
}
// Update the breadcrumb trail to show the current sequence and percentage.
function updateBreadcrumbs(nodeArray, percentageString) {
// Data join; key function combines name and depth (= position in sequence).
var g = d3.select("#trail")
.selectAll("g")
.data(nodeArray, function(d) { return d.name + d.depth; });
// Add breadcrumb and label for entering nodes.
var entering = g.enter().append("svg:g");
entering.append("svg:polygon")
.attr("points", breadcrumbPoints)
.style("fill", function(d) { return colors[d.name]; });
entering.append("svg:text")
.attr("x", (b.w + b.t) / 2)
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; });
// Set position for entering and updating nodes.
g.attr("transform", function(d, i) {
return "translate(" + i * (b.w + b.s) + ", 0)";
});
// Remove exiting nodes.
g.exit().remove();
// Now move and update the percentage at the end.
d3.select("#trail").select("#endlabel")
.attr("x", (nodeArray.length + 0.5) * (b.w + b.s))
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(percentageString);
// Make the breadcrumb trail visible, if it's hidden.
d3.select("#trail")
.style("visibility", "");
}
function drawLegend() {
// Dimensions of legend item: width, height, spacing, radius of rounded rect.
var li = {
w: 75, h: 30, s: 3, r: 3
};
var legend = d3.select("#legend").append("svg:svg")
.attr("width", li.w)
.attr("height", d3.keys(colors).length * (li.h + li.s));
var g = legend.selectAll("g")
.data(d3.entries(colors))
.enter().append("svg:g")
.attr("transform", function(d, i) {
return "translate(0," + i * (li.h + li.s) + ")";
});
g.append("svg:rect")
.attr("rx", li.r)
.attr("ry", li.r)
.attr("width", li.w)
.attr("height", li.h)
.style("fill", function(d) { return d.value; });
g.append("svg:text")
.attr("x", li.w / 2)
.attr("y", li.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.key; });
}
function toggleLegend() {
var legend = d3.select("#legend");
if (legend.style("visibility") == "hidden") {
legend.style("visibility", "");
} else {
legend.style("visibility", "hidden");
}
}
// Take a 2-column CSV and transform it into a hierarchical structure suitable
// for a partition layout. The first column is a sequence of step names, from
// root to leaf, separated by hyphens. The second column is a count of how
// often that sequence occurred.
function buildHierarchy(csv) {
var root = {"name": "root", "children": []};
for (var i = 0; i < csv.length; i++) {
var sequence = csv[i][0];
var size = +csv[i][1];
if (isNaN(size)) { // e.g. if this is a header row
continue;
}
var parts = sequence.split("-");
var currentNode = root;
for (var j = 0; j < parts.length; j++) {
var children = currentNode["children"];
var nodeName = parts[j];
var childNode;
if (j + 1 < parts.length) {
// Not yet at the end of the sequence; move down the tree.
var foundChild = false;
for (var k = 0; k < children.length; k++) {
if (children[k]["name"] == nodeName) {
childNode = children[k];
foundChild = true;
break;
}
}
// If we don't already have a child node for this branch, create it.
if (!foundChild) {
childNode = {"name": nodeName, "children": []};
children.push(childNode);
}
currentNode = childNode;
} else {
// Reached the end of the sequence; create a leaf node.
childNode = {"name": nodeName, "size": size};
children.push(childNode);
}
}
}
return root;
};
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Flow for G1 customers</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
<link rel="stylesheet" type="text/css"
href="https://fonts.googleapis.com/css?family=Open+Sans:400,600">
<link rel="stylesheet" type="text/css" href="sequences.css"/>
</head>
<body>
<div id="main">
<div id="sequence"></div>
<div id="chart">
<div id="explanation" style="visibility: hidden;">
<span id="percentage"></span><br/>
of G1 customers follow this flow.
</div>
</div>
</div>
<div id="sidebar">
<input type="checkbox" id="togglelegend"> Legend<br/>
<div id="legend" style="visibility: hidden;"></div>
</div>
<script type="text/javascript" src="sequences.js"></script>
<script type="text/javascript">
// Hack to make this example display correctly in an iframe on bl.ocks.org
d3.select(self.frameElement).style("height", "700px");
</script>
</body>
</html>
Had the same issue, though I initially thought it is because of security restrictions of browser, that wasn't the case. It worked when I added the charset to the script tag as shown below:
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
The same is shown in the d3 docs, though it doesn't mention this issue specifically: http://d3js.org/
Yes, having it locally works too.
<script src="d3.min.js"></script>
Here is the full example:
<!doctype html>
<html>
<head>
<title>D3 tutorial</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<!--<script src="d3.min.js"></script>-->
</head>
<body>
<script>
var canvas = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500);
var circle = canvas.append("circle")
.attr("cx",250)
.attr("cy", 250)
.attr("r", 50)
.attr("fill", "red");
</script>
</body>
</html>
There may be security restrictions that prevent your browser from downloading the D3 script. What you can do is to download the scripts, place them in the same folder as your files, and change the referenced paths in your source.
You may also need to add:
<meta charset="utf-8">
or
<meta content="utf-8" http-equiv="encoding">
to your head section
in case browser does not prevent it from downloading and still getting the error, d3.js should be placed before jquery.
I just moved my reference to the package as the first import in my head tag:
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
...
...
</head>
Seemed to work for me
Replace <meta charset="ISO-8859-1"> with <meta charset="UTF-8">
I had to do a grunt build to get get rid of this error. (Using Yeoman and Ember.js.)
And for JavaScript noobs like me - problem could be that you don't import it correctly. Try reading import docs and things like:
import * as d3 from 'd3-transition'
If you are using Visual Studio you can go to Tools -> Options -> Text Editor -> JavaScript -> IntelliSense and check the box "Download remote references". That did the trick for me.
UPDATE: there is now a d3-webpack-loader package which makes it easy to load d3 in webpack. I am not the creator of the package, I've only used it to see if it works. Here's a quick example.
// Install the loader
npm install --save d3-webpack-loader
// Install the d3 microservices you need
npm install --save d3-color
npm install --save d3-selection
In our entry.js file we'll require d3 using the d3-webpack-loader with:
const d3 = require('d3!');
and can then use some of the d3 methods with:
d3.selectAll("p").style("color", d3.color("red").darker());
Super late to this response but none of the above solutions worked out for me. I found a fix though!
I am on macOS Catalina. For some bizarre reason, it turned out to be a decompression/unpack issue with the .tgz file from Observable's website. I use an application called The Unarchiver to decompress files, but in this case, the .tgz file did not properly unpack. There was a folder and file missing compared to a friend's computer not using the same program.
Solution: I unpacked .tgz without a third party program – just used macOS (simply double clicking on the file). Then, I loaded the page locally and it worked!
If double clicking on the file fails to unpack, try running tar -xzf filename.tgz in Terminal.
I assume that you are importing the d3 from online.
In your HTML, make sure that you are importing the d3 before connecting your JavaScript file.
// Importing D3.js
<script src="https://d3js.org/d3.v5.min.js" charset="utf-8" defer></script>
// Importing D3-Scale
<script src="https://d3js.org/d3-scale.v3.min.js"></script>
// Connecting my JS file
<script src="app.js" defer></script>

D3.js code in Reveal.js slide

I'm trying to make D3.js work on Reveal.js slides, but I can't get it to run even the most basic snippet:
<section>
<h2>Title</h2>
<div id="placeholder"></div>
<script type="text/javascript">
d3.select("#placeholder").append("p").text("TEST");
</script>
</section>
Doesn't show the "TEST" word. What am I doing wrong?
Okay here we go.
I have made a basic example with Reveal.js & D3.js and it works well.
There are two slides
First slide contains Bar chart
Second slide renders Bubble chart by taking data from a json input file
Your code works fine if it is placed outside of the section at the bottom. I have placed all D3.js code at the end of the html page before body closer.
The folder structure is show below (in snapshot)
I placed my JS inside the HTML (in order to make it easier to read/comprehend)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Reveal.js with D3 JS</title>
<link rel="stylesheet" href="css/reveal.min.css">
<link rel="stylesheet" href="css/theme/default.css" id="theme">
<style>
.chart rect {
fill: #63b6db;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
text {
font: 10px sans-serif;
}
</style>
</head>
<body>
<div class="reveal">
<div class="slides">
<section>
<h2>Barebones Presentation</h2>
<p>This example contains the bare minimum includes and markup required to run a reveal.js presentation.</p>
<svg class="chart"></svg>
</section>
<section id="sect2">
<h2>No Theme</h2>
<p>There's no theme included, so it will fall back on browser defaults.</p>
<svg class="bubleCharts"></svg>
</section>
</div>
</div>
<script src="js/reveal.min.js"></script>
<script>
Reveal.initialize();
</script>
<script src="js/d3.min.js"></script>
<script type="text/javascript">
//------ code to show D3 Bar Chart on First Slide-------
var data = [44, 28, 15, 16, 23, 5];
var width = 420,
barHeight = 20;
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, width]);
var chart = d3.select(".chart")
.attr("width", width)
.attr("height", barHeight * data.length);
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d; });
//---Code below will show Bubble Charts on the secon Slide -------
var diameter = 560,
format = d3.format(",d"),
color = d3.scale.category20c();
var bubble = d3.layout.pack()
.sort(null)
.size([diameter, diameter])
.padding(1.5);
var svg = d3.select(".bubleCharts")
.attr("width", diameter)
.attr("height", diameter)
.attr("class", "bubble");
d3.json("flare.json", function(error, root) {
var node = svg.selectAll(".node")
.data(bubble.nodes(classes(root))
.filter(function(d) { return !d.children; }))
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
node.append("title")
.text(function(d) { return d.className + ": " + format(d.value); });
node.append("circle")
.attr("r", function(d) { return d.r; })
.style("fill", function(d) { return color(d.packageName); });
node.append("text")
.attr("dy", ".3em")
.style("text-anchor", "middle")
.text(function(d) { return d.className.substring(0, d.r / 3); });
});
// Returns a flattened hierarchy containing all leaf nodes under the root.
function classes(root) {
var classes = [];
function recurse(name, node) {
if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
else classes.push({packageName: name, className: node.name, value: node.size});
}
recurse(null, root);
return {children: classes};
}
d3.select(self.frameElement).style("height", diameter + "px");
</script>
</body>
</html>
Output/results
Slide 1
Slide 2
Download complete code https://github.com/aahad/D3.js/tree/master/Reveal JS with D3 JS
To learn more about how Bar Chart or Bubble Chart code works: check followings:
Bubble Chart examples: http://bl.ocks.org/mbostock/4063269
Bar Chart examples: http://bost.ocks.org/mike/bar/
Both existing answers are fine, but I'd like to point out a 3rd approach that worked for me and has some advantages.
Reveal.js has an event system and it also works with the per-slide data states.
This means that you can have a separate javascript block for each slide and have it execute only when that slide is loaded. This lets you do D3-based animations upon load of the slide and has the further advantage of placing the code for the slide closer to the text/markup of it.
For example, you could set your slide like this. Note the data-state attribute:
<section data-state="myslide1">
<h2>Blah Blah</h2>
<div id="slide1d3container"></div>
</section>
And then have an associated script block:
<script type="text/javascript">
Reveal.addEventListener( 'myslide1', function() {
var svg = d3.select("#slide1d3container").append("svg")
// do more d3 stuff
} );
</script>
Here's an example of a presentation that uses this technique:
http://explunit.github.io/d3_cposc_2014.html
I found out by myself. Of course I cannot match against ids that are not loaded yet: it works if I put the d3 javascript code after the Reveal.initialize script block at the end of the index.html file.

Categories