Making a simple table Using D3 in meteor - d3.js

I am testing d3.js in meteor.
While trying to make a simple table for test,I met a trouble.
Here is my codes
<template name="ob">
<h4>Table test- {{name}}</h4>
<svg id="obTable"><table><tr></tr></table></svg>
</template>
And below is javascript file for template above...
Template.ob.onRendered(function() {
//Width and height
var w = 600;
var h = 350;
//Define key function, to be used when binding data
var key = function (d) {
return d.index;
};
//Create SVG element
var svg = d3.select("#obTable")
.attr("width", w)
.attr("height", h);
var dataset = require('../data/ob.json');
// var dataset = Bars.find({}).fetch();
//Select…
var table = svg.selectAll('table').append('table')
.style("border-collapse", "collapse")
.style("border", "2px black solid");
// .data(dataset, key);
console.log(table);
var rows = table.selectAll('tr')
.data(dataset, key)
.enter()
.append('tr');
console.log(rows);
rows.selectAll('td')
.data(function(d){ console.log(d); return d;} )
.enter()
.append('td')
.text(function(d) {console.log("here"); return d;})
.style("border", "1px black solid")
.style("padding", "10px")
.style("font-size","12px");
});
I've got no errors from those code above, but when I execute my app, I could not see any table or table contents. ( since I can see in contents well, I am sure there is no problem on showing template itself)
Things that I can't most understand is that I can see log messages from rows.selectAll('td').data(function(d){ console.log(d); return d;} ) well, but I can't see any log from .text(function(d) {console.log("here"); return d;})
I doubt this could be a reason for not showing table, but could not solve further.
I installed d3 from npm and it's version is 4.10.0
Any advice would be greatly appreciated.

I had this problem as well. Issue is that the dom is getting rewritten due to reactive updates, and your on render select is getting destroyed.
How I solved this was to do a template helper at the end of the template. Something like this...
<template name="ob">
<h4>Table test- {{name}}</h4>
<svg id="obTable"><table><tr></tr></table></svg>
{{doD3Stuff}}
</template>
Template.ob.helpers(function() {
doD3Stuff: function() {
// all your on render code here
//Width and height
var w = 600;
var h = 350;
//Define key function, to be used when binding data
var key = function (d) {
return d.index;
};
//Create SVG element
var svg = d3.select("#obTable")
.attr("width", w)
.attr("height", h);
var dataset = require('../data/ob.json');
// var dataset = Bars.find({}).fetch();
//Select…
var table = svg.selectAll('table').append('table')
.style("border-collapse", "collapse")
.style("border", "2px black solid");
// .data(dataset, key);
console.log(table);
var rows = table.selectAll('tr')
.data(dataset, key)
.enter()
.append('tr');
console.log(rows);
rows.selectAll('td')
.data(function(d){ console.log(d); return d;} )
.enter()
.append('td')
.text(function(d) {console.log("here"); return d;})
.style("border", "1px black solid")
.style("padding", "10px")
.style("font-size","12px");
}

Related

How can i get the key of an element in stack-layout in d3?

I want to add a toolkit that show the type of the disaster, which is the key of the stack datum, how can i get it?
The format of .csv file is like this: (Forgive me can not take pictures)
AllNaturalDisasters,Drought,Earthquake,ExtremeTemperature,ExtremeWeather,Flood,Impact,Landslide,MassMovementDry,VolcanicActivity,Wildfire,Year
5,2,null,null,1,1,null,null,null,1,null,1900
2,null,2,null,null,null,null,null,null,null,null,1901
Here I create a stack
var stack = d3.stack()
.keys(["Drought", "Earthquake", "ExtremeTemperature", "ExtremeWeather", "Flood", "Impact", "Landslide", "MassMovementDry", "VolcanicActivity", "Wildfire"]);
and then I pass it my data:var series = stack(dataset);. dataset is the all data from the csv file. Then I create a chart using stack-layout, like this:
var groups = svg.selectAll("g")
.data(series)
.enter()
.append("g")
.style("fill", function(d, i) {
return colors(i);
});
var rects = groups.selectAll("rect")
.data(function(d) { return d; })
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return yScale(d[1]);
})
.attr("height", function(d) {
return yScale(d[0]) - yScale(d[1]);
})
.attr("width", xScale.bandwidth())
.append("title")
.text(function (d) {
return d.data.Year;
});
The problem is right here:
.append("title")
.text(function (d) {
return d.data.Year;
});
I want to add a toolkit to show the type of the disaster, which is the key of this datum in series , how can I get it instead of the year?!
Each rectangle contains information on the column (year of disaster), but each g has information on the "row" (type of disaster).
The stack produces a nested array, the parent level (which we use to create the g elements) contains the key, or type of disaster
The child level represents the columns, which contains the year.
The grandchild level just contains individual rectangles.
So, we can get a key by selecting the parent g:
.append("title")
.text(function() {
var rect = this.parentNode; // the rectangle, parent of the title
var g = rect.parentNode; // the g, parent of the rect.
return d3.select(g).datum().key; // now we get the key.
})
Of course this could be simplified a bit, but I broke it out to comment it better.
This allows for more flexible sorting - rather than relying on fixed indexes.
Here it is using your data:
var csv = d3.csvParse(d3.select("pre").text());
var stack = d3.stack().keys(["Drought", "Earthquake", "ExtremeTemperature", "ExtremeWeather", "Flood", "Impact", "Landslide", "MassMovementDry", "VolcanicActivity", "Wildfire"]);
var series = stack(csv);
var colors = d3.scaleOrdinal()
.range(d3.schemeCategory10);
var xScale = d3.scaleBand()
.domain([0,1])
.range([0,300])
var yScale = d3.scaleLinear()
.domain([0,6])
.range([200,0]);
var svg = d3.select("svg");
var groups = svg.selectAll("g")
.data(series)
.enter()
.append("g")
.style("fill", function(d, i) {
return colors(i);
});
var rects = groups.selectAll("rect")
.data(function(d) { return d; })
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return yScale(d[1]);
})
.attr("height", function(d) {
return yScale(d[0]) - yScale(d[1]);
})
.attr("width", xScale.bandwidth())
.append("title")
.text(function (d) {
var rect = this.parentNode;
var g = rect.parentNode;
return d3.select(g).datum().key;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="400" height="300"></svg>
<pre>AllNaturalDisasters,Drought,Earthquake,ExtremeTemperature,ExtremeWeather,Flood,Impact,Landslide,MassMovementDry,VolcanicActivity,Wildfire,Year
5,2,0,0,1,1,0,0,0,1,0,1900
2,0,2,0,0,0,0,0,0,0,0,1901</pre>
Well, I have fixed this problem by a very 'low' method. I have created a simple function:
function getKeys(d) {
return series[parseInt(groups.selectAll("rect").data().indexOf(d) / series[0].length)].key;
}
Well, it so simple and crude, and I still want to know a more efficient method!!!

D3 - Using JSON data to create multiple bars

I'm learning D3 and have JSON data. I want to build multiple bars from this JSON data to draw graph like this already built in excel. I can draw one line of Pax_Rev on SVG but I'm not sure how to add other lines from the data. When I do console.log(dataset.length), it shows me 0 which means only one item in dataset which is expected.
<script>
var dataset = [{"Pax_Rev": 1000, "Crg_Rev": 500,
"Fixed_Costs": 800, "Variable_Costs": 200}];
var width = 500;
var height = 1000;
var barPadding = 1;
var svg = d3.select("body")
.append("svg")
.append("g")
.attr("width", width)
.attr("height", height)
.attr("class", "svg")
svg3.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", 0)
.attr("y", function(d){
return height - d.Pax_Rev // How to add other items like Crg_Rev etc?
})
.attr("width", 20)
.attr("height", function(d){
return d.Pax_Rev
});
</script>
As I explained in your previous question, this is the expected behaviour. Since you have just one object in your data array, D3 "enter" selection will create just one element.
If you look at the API, you'll see that selection.data():
Joins the specified array of data with the selected elements[...] The specified data is an array of arbitrary values (e.g., numbers or objects). (emphases mine)
Therefore, we have to convert that huge object in several objects. This is one of several possible approaches:
var dataset = [{
"Pax_Rev": 1000,
"Crg_Rev": 500,
"Fixed_Costs": 800,
"Variable_Costs": 200
}];
var data = [];
for (var key in dataset[0]) {
data.push({
category: key,
value: dataset[0][key]
})
}
console.log(data)
Now, we have a data array, with several objects, one for each bar, and we can create our bar chart.
Here is a demo:
var dataset = [{
"Pax_Rev": 1000,
"Crg_Rev": 500,
"Fixed_Costs": 800,
"Variable_Costs": 200
}];
var data = [];
for (var key in dataset[0]) {
data.push({
category: key,
value: dataset[0][key]
})
}
var svg = d3.select("svg");
var yScale = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return d.value
})])
.range([120, 10]);
var xScale = d3.scaleBand()
.domain(data.map(function(d) {
return d.category
}))
.range([40, 280])
.padding(0.2);
var rects = svg.selectAll(null)
.data(data)
.enter()
.append("rect")
.attr("fill", "steelblue")
.attr("x", function(d) {
return xScale(d.category)
})
.attr("width", xScale.bandwidth())
.attr("y", function(d) {
return yScale(d.value)
})
.attr("height", function(d) {
return 120 - yScale(d.value)
});
var yAxis = d3.axisLeft(yScale);
var xAxis = d3.axisBottom(xScale);
svg.append("g").attr("transform", "translate(40,0)").call(yAxis);
svg.append("g").attr("transform", "translate(0,120)").call(xAxis);
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

d3 treemap graphic don't recognize enter() and exit() data correctly

I'm trying to create dynamic treemap graphic with lovely d3.js library.
Here are sample of my code
element = d3.select(element[0]);
var margin = 10,
width = parseInt(element.style('width')) - margin * 2,
height = parseInt(element.style('height')) - margin * 2;
var color = d3.scale.category10();
var canvas = d3.select('.treemap').append('svg')
.attr('width', width)
.attr('height', height)
.attr('transform', 'translate(-.5,-.5)')
.style('margin', margin);
var treemap = d3.layout.treemap()
.size([width, height])
.value(function(d) { return d.value; })
.sticky(false);
function redraw(data) {
d3.selectAll('.cell').remove();
var treemapData = {};
treemapData.children = data.map(function(d) {
return {
name: d.name,
value: d.value
};
});
var leaves = treemap(treemapData);
var cells = canvas.selectAll("g")
.data(leaves);
var cellsEnter = cells.enter()
.append('rect')
.attr('class', 'cell')
.attr('x', function(d) { return d.x; })
.attr('y', function(d) { return d.y; })
.attr('width', function(d) { return d.dx; })
.attr('height', function(d) { return d.dy; })
.attr('fill', function(d) { return d.children ? null : color(d.name); })
.attr('stroke', "#fff")
.style('fill-opacity', 0);
console.log(cells.exit(), cells.enter());
}
And here I have stucked.
console.log() shows that whole new data are enter(), and none are exit() !
Input data presents like
[{value: 590, name:"A1"}, {...}, ...]
without root object field, so that's why I remapped data in treemapData object.
Тhanks that you at least spent your time for reading this post so far, hope you have any suggestions.
UDP. you can check working version of my code here: https://jsfiddle.net/qtbfm08k/
The following works:
remove d3.selectAll('.cell').remove();
use the code below
See the fiddle: https://jsfiddle.net/b6meLedn/4/
var cells = canvas.selectAll('.cell') //select all cells
.data(leaves); //map the data
cells.exit().remove(); //remove old extra elements
cells.enter()
.append('rect') //create new rectangles as necessary
.attr('class', 'cell')
cells //take all cells (old cells that have new data+extra new cells)
.attr('x', function(d) { return d.x; })
...

Adding text on each bar of histogram

I have problem adding text in my histogram. I can do this in more simple example.
I try to do this:
// try to add bar value
var barnum = g.selectAll('text')
.data(layout)
.enter()
.append("text")
.attr('y',-10)
.attr('x',10)
.attr("text-anchor", "middle")
.style("fill","black")
.text('testtest')
.style("pointer-events", "none")
;
barnum.transition();
I can't see any text in my figure. The code include definition is here:
var dateFormat = d3.time.format("%Y-%m-%d");
var g;
var data;
var margin = {top: 30, right: 30, bottom: 80, left: 80},
width = 500 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var cx = 10;
var numberBins = 5;
var dispatch = d3.dispatch(chart, "hover");
function chart(container) {
g = container;
update();
}
chart.update = update;
function update() {
// create hist layout
var hist = d3.layout.histogram()
.value(function(d) { return d.selectvar })
.range([d3.min(data, function(d){ return d.selectvar }) , d3.max(data, function(d){ return d.selectvar }) ])
.bins(numberBins);
var layout = hist(data);
var maxLength = d3.max(layout, function(d) { return d.length });
var widthScale = d3.scale.linear()
.domain([0, maxLength])
.range([0, width])
var yScale = d3.scale.ordinal()
.domain(d3.range(numberBins))
.rangeBands([height, 0], 0)
var colorScale = d3.scale.category20();
// create svg
var rects = g.selectAll("rect")
.data(layout)
rects.enter().append("rect")
rects .transition()
.duration(500)
.attr({
y: function(d,i) {
return yScale(i)
},
x: 50,
height: yScale.rangeBand(),
width: function(d,i) {
return widthScale(d.length)
},
fill: function(d, i) { return colorScale(i) }
});
rects.exit().transition().remove();
// try to add bar value
var barnum = g.selectAll('text')
.data(layout)
.enter()
.append("text")
.attr('y',-10)
.attr('x',10)
.attr("text-anchor", "middle")
.style("fill","black")
.text('testtest')
.style("pointer-events", "none")
;
barnum.transition();
is there something wrong with my way to create svg element? I found out some successful case use append('g') from the beginning. New to d3.js! thank you.
You're using d3.dispatch, which is documented on a page titled Internals. That doesn't mean you shouldn't use it, but rather, it shouldn't be your first choice.
You're correct that there's "something wrong with my way to create svg element" -- you're not creating one! Try:
var svg = d3.select("body").append("svg");
var g = svg.append("g");
At this point, you need to have a good understanding of the DOM, the SVG standard, CSS selectors, and D3's selection API to make things work. You don't tell D3 to put labels on your bars and that's it. You have to instruct it what elements to create, and where, keeping track of translates and offsets and stuff like that. You're best off copying and studying one of Mike Bostock's many examples.
D3 is not learned quickly. You need to invest time learning it before you can make any chart you like.

d3.js reusable pie chart with dynamic updates

I'm trying to create a reusable pie chart with dynamic transitions as a learning task. I'm working off of the d3.js resuable components e-book by Chris Viau.
The problem I'm having is basically its not updating, but creating multiple pie charts. I'm wondering if I'm not understanding how d3.dispatch works or whether I've messed something up in the way the pie char should work. It creates multiple circles instead of dynamically updating a single pie chart with random values.
here is my jsfiddle.
http://jsfiddle.net/seoulbrother/Upcr5/
thanks!
js code below:
d3.edge = {};
d3.edge.donut = function module() {
var width = 460,
height = 300,
radius = Math.min(width, height) / 2;
var color = d3.scale.category20();
var dispatch = d3.dispatch("customHover");
function graph(_selection) {
_selection.each(function(_data) {
var pie = d3.layout.pie()
.value(function(_data) { return _data; })
.sort(null);
var arc = d3.svg.arc()
.innerRadius(radius - 100)
.outerRadius(radius - 50);
if (!svg){
var svg = d3.select(this).append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
}
var path = svg.selectAll("path")
.data(pie)
.enter().append("path")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc)
.each(function(d) {this._current = d;} );
path.transition()
.ease("elastic")
.duration(750)
.attrTween("d", arcTween);
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function(t) {
return arc(i(t));
};
}
});
}
d3.rebind(graph, dispatch, "on");
return graph;
}
donut = d3.edge.donut();
var data = [1, 2, 3, 4];
var container = d3.select("#viz").datum(data).call(donut);
function update(_data) {
data = d3.range(~~(Math.random() * 20)).map(function(d, i) {
return ~~(Math.random() * 100);
});
container.datum(data).transition().ease("linear").call(donut);
}
update();
setTimeout( update, 1000);
The main reason for multiple SVGs appearing is that you're not checking if there is one already correctly. You're relying on the variable svg being defined, but define it only after checking whether it is defined.
The better way is to select the element you're looking for and check whether that selection is empty:
var svg = d3.select(this).select("svg > g");
if (svg.empty()){ // etc
In addition, you need to handle the update and exit selections in your code in addition to the enter selection. Complete jsfiddle here.

Resources