d3 Bar Chart Add Margins - javascript

I would like to make this d3 bar chart (ignore the different colors, that's for grouping which is not what I'm talking about):
Look like this javascript bar chart (specifically, how it has each instance broken up into "links" or "blocks" i.e. there is spacing between each item):
I can do this in javascript fairly easily but I am not sure how to do this in d3.
Can anyone provide any examples of how to break down each item as shown in the graph above?
I have tried this so far:
.append("rect")
.style("margin", "20")
This is the source for the d3 chart: https://jsfiddle.net/mq2jcfz0/
<!DOCTYPE html>
<html>
<head>
<script src="http://mbostock.github.com/d3/d3.v2.js"></script>
<title>barStack</title>
<style>
.axis text {
font: 10px sans-serif;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
</head>
<body>
<script type="text/javascript" >
function barStack(d) {
var l = d[0].length
while (l--) {
var posBase = 0, negBase = 0;
d.forEach(function(d) {
d=d[l]
d.size = Math.abs(d.y)
if (d.y<0) {
d.y0 = negBase
negBase-=d.size
} else
{
d.y0 = posBase = posBase + d.size
}
})
}
d.extent= d3.extent(d3.merge(d3.merge(d.map(function(e) { return e.map(function(f) { return [f.y0,f.y0-f.size]})}))))
return d
}
/* Here is an example */
var data = [[{y:3},{y:6},{y:-3}],
[{y:4},{y:-2},{y:-9}],
[{y:10},{y:-3},{y:4}]]
var h=500
,w=500
,margin=10
,color = d3.scale.category10()
,x = d3.scale.ordinal()
.domain(['abc','abc2','abc3'])
.rangeRoundBands([margin,w-margin], .1)
,y = d3.scale.linear()
.range([h-margin,0+margin])
,xAxis = d3.svg.axis().scale(x).orient("bottom").tickSize(6, 0)
,yAxis = d3.svg.axis().scale(y).orient("left")
barStack(data)
y.domain(data.extent)
svg = d3.select("body")
.append("svg")
.attr("height",h)
.attr("width",w)
svg.selectAll(".series").data(data)
.enter().append("g").classed("series",true).style("fill", function(d,i) { return color(i)})
.selectAll("rect").data(Object)
.enter().append("rect")
.attr("x",function(d,i) { return x(x.domain()[i])})
.attr("y",function(d) { return y(d.y0)})
.attr("height",function(d) { return y(0)-y(d.size)})
.attr("width",x.rangeBand())
svg.append("g").attr("class","axis x").attr("transform","translate (0 "+y(0)+")").call(xAxis)
svg.append("g").attr("class","axis y").attr("transform","translate ("+x(margin)+" 0)").call(yAxis)
</script>
</body>
</html>

You will need to work with the barStack function that deals with arranging the data to stack the bars.
You just have to move rects position like this:
var barPad = 0.5;
function barStack(d) {
var l = d[0].length
while (l--) {
var posBase = 0, negBase = 0;
d.forEach(function(d) {
d=d[l]
d.size = Math.abs(d.y)
if (d.y<0) {
d.y0 = negBase - barPad
negBase-=d.size + barPad
} else
{
d.y0 = posBase = posBase + d.size + barPad
}
})
}
d.extent= d3.extent(d3.merge(d3.merge(d.map(function(e) { return e.map(function(f) { return [f.y0,f.y0-f.size]})}))))
return d
}

Related

canvg SVG rendering to wrong format

I have a piechart with labels and legend which looks fine in SVG but as soon as I use canvg to transform it to canvas some formats are missing / get wrong.
SVG:
Canvas:
I already inline the CSS to apply all CSS settings but still the format does not match.
Any ideas?
Is this a (canvg) bug or am I doing s.th. wrong?
var columns = ['data11', 'data2', 'data347', 'data40098'];
var data = [150, 250, 300, 50];
var colors = ['#0065A3', '#767670', '#D73648', '#7FB2CE', '#00345B'];
var padding = 5;
/**
* global C3Styles object
*/
var C3Styles = null;
var legendData = [];
var sumTotal = 0
//prepare pie data
var columnData = [];
var columnNames = {};
for (i = 0; i < columns.length; i++) {
columnData.push([columns[i]].concat(data[i]));
var val = (Array.isArray(data[i])) ? data[i].reduce(function(pv, cv) {
return pv + cv;
}, 0) : data[i];
sumTotal += val;
legendData.push({
id: columns[i],
value: val,
ratio: 0.0
});
}
legendData.forEach(function(el, i) {
el.ratio = el.value / sumTotal
columnNames[el.id] = [el.id, d3.format(",.0f")(el.value), d3.format(",.1%")(el.ratio)].join(';');
});
var chart = c3.generate({
bindto: d3.select('#chart'),
data: {
columns: [
[columns[0]].concat(data[0])
],
names: columnNames,
type: 'pie',
},
legend: {
position: 'right',
show: true
},
pie: {
label: {
threshold: 0.001,
format: function(value, ratio, id) {
return [id, d3.format(",.0f")(value), "[" + d3.format(",.1%")(ratio) + "]"].join(';');
}
}
},
color: {
pattern: colors
},
onrendered: function() {
redrawLabelBackgrounds();
redrawLegend();
}
});
function addLabelBackground(index) {
/*d3.select('#chart').select("g.c3-target-" + columns[index].replace(/\W+/g, '-')+".c3-chart-arc")
.insert("rect", "text")
.style("fill", colors[index]);*/
var p = d3.select('#chart').select("g.c3-target-" + columns[index].replace(/\W+/g, '-') + ".c3-chart-arc");
var g = p.append("g");
g.append("rect")
.style("fill", colors[index]);
g.append(function() {
return p.select("text").remove().node();
});
}
for (var i = 0; i < columns.length; i++) {
if (i > 0) {
setTimeout(function(column) {
chart.load({
columns: [
columnData[column],
]
});
//chart.data.names(columnNames[column])
addLabelBackground(column);
}, (i * 5000 / columnData.length), i);
} else {
addLabelBackground(i);
}
}
function redrawLegend() {
d3.select('#chart').selectAll(".c3-legend-item > text").each(function() {
// get d3 node
var legendItem = d3.select(this);
var legendItemNode = legendItem.node();
//check if label is drawn
if (legendItemNode) {
if (legendItemNode.childElementCount === 0 && legendItemNode.innerHTML.length > 0) {
//build data
var data = legendItemNode.innerHTML.split(';');
legendItem.text("");
//TODO format legend dynamically depending on text
legendItem.append("tspan")
.text(data[0] + ": ")
.attr("class", "id-row")
.attr("text-anchor", "start");
legendItem.append("tspan")
.text(data[1] + " = ")
.attr("class", "value-row")
.attr("x", 160)
.attr("text-anchor", "end");
legendItem.append("tspan")
.text(data[2])
.attr("class", "ratio-row")
.attr("x", 190)
.attr("text-anchor", "end");
}
}
});
d3.select('#chart').selectAll(".c3-legend-item > rect").each(function() {
var legendItem = d3.select(this);
legendItem.attr("width", 190);
});
}
function redrawLabelBackgrounds() {
//for all label texts drawn yet
//for all label texts drawn yet
d3.select('#chart').selectAll(".c3-chart-arc > g > text").each(function(v) {
// get d3 node
var label = d3.select(this);
var labelNode = label.node();
//check if label is drawn
if (labelNode) {
if (labelNode.childElementCount === 0 && labelNode.innerHTML.length > 0) {
//build data
var data = labelNode.innerHTML.split(';');
label.text("");
data.forEach(function(i, n) {
label.append("tspan")
.text(i)
.attr("dy", (n === 0) ? 0 : "1.2em")
.attr("x", 0)
.attr("text-anchor", "middle");
}, label);
}
//check if element is visible
if (d3.select(labelNode.parentNode).style("display") !== 'none') {
//get pos of the label text
var pos = label.attr("transform").match(/-?\d+(\.\d+)?/g);
if (pos) {
// TODO: mofify the pos of the text
// pos[0] = (pos[0]/h*90000);
// pos[1] = (pos[1]/h*90000);
// remove dy and move label
//d3.select(this).attr("dy", 0);
//d3.select(this).attr("transform", "translate(" + pos[0] + "," + pos[1] + ")");
//get surrounding box of the label
var bbox = labelNode.getBBox();
//now draw and move the rects
d3.select(labelNode.parentNode).select("rect")
.attr("transform", "translate(" + (pos[0] - (bbox.width + padding) / 2) +
"," + (pos[1] - bbox.height / labelNode.childElementCount) + ")")
.attr("width", bbox.width + padding)
.attr("height", bbox.height + padding);
}
}
}
});
}
document.getElementById("exportButton").onclick = function() {
exportChartToImage();
};
function exportChartToImage() {
var createImagePromise = new Promise(function(resolve, reject) {
var images = [];
d3.selectAll('svg').each(function() {
if (this.parentNode) {
images.push(getSvgImage(this.parentNode, true));
}
});
if (images.length > 0)
resolve(images);
else
reject(images);
});
createImagePromise.then(function(images) {
/*images.forEach(function(img, n) {
img.toBlob(function(blob) {
saveAs(blob, "image_" + (n + 1) + ".png");
});
});*/
})
.catch(function(error) {
throw error;
});
};
/**
* Converts a SVG-Chart to a canvas and returns it.
*/
function getSvgImage(svgContainer) {
var svgEl = d3.select(svgContainer).select('svg').node();
var svgCopyEl = svgEl.cloneNode(true);
if (!svgCopyEl)
return;
d3.select("#svgCopyEl").selectAll("*").remove();
d3.select("#svgCopyEl").node().append(svgCopyEl);
//apply all CSS styles to SVG
/* taken from https://gist.github.com/aendrew/1ad2eed6afa29e30d52e#file-exportchart-js
and changed from, angular to D3 functions
*/
/* Take styles from CSS and put as inline SVG attributes so that Canvg
can properly parse them. */
if (!C3Styles) {
var chartStyle;
// Get rules from c3.css
var styleSheets = document.styleSheets;
for (var i = 0; i <= styleSheets.length - 1; i++) {
if (styleSheets[i].href && (styleSheets[i].href.indexOf('c3.min.css') !== -1 || styleSheets[i].href.indexOf('c3.css') !== -1)) {
try {
if (styleSheets[i].rules !== undefined) {
chartStyle = styleSheets[i].rules;
} else {
chartStyle = styleSheets[i].cssRules;
}
break;
}
//Note that SecurityError exception is specific to Firefox.
catch (e) {
if (e.name == 'SecurityError') {
console.log("SecurityError. Cant read: " + styleSheets[i].href);
continue;
}
}
}
if (chartStyle !== null && chartStyle !== undefined) {
C3Styles = {};
var selector;
// Inline apply all the CSS rules as inline
for (i = 0; i < chartStyle.length; i++) {
if (chartStyle[i].type === 1) {
selector = chartStyle[i].selectorText;
var styleDec = chartStyle[i].style;
for (var s = 0; s < styleDec.length; s++) {
C3Styles[styleDec[s]] = styleDec[styleDec[s]];
}
}
}
}
}
}
if (C3Styles) {
d3.select(svgCopyEl).selectAll('.c3:not(.c3-chart):not(path)').style(C3Styles);
}
// SVG doesn't use CSS visibility and opacity is an attribute, not a style property. Change hidden stuff to "display: none"
d3.select(svgCopyEl).selectAll('*')
.filter(function(d) {
return d && d.style && (d.style('visibility') === 'hidden' || d.style('opacity') === '0');
})
.style('display', 'none');
//fix weird back fill
d3.select(svgCopyEl).selectAll("path").attr("fill", "none");
//fix no axes
d3.select(svgCopyEl).selectAll("path.domain").attr("stroke", "black");
//fix no tick
d3.select(svgCopyEl).selectAll(".tick line").attr("stroke", "black");
//apply svg text fill, set color
d3.select(svgCopyEl).selectAll("text:not(.c3-empty):not(.c3-axis)").attr("opacity", 1);
var canvasComputed = d3.select("#canvasComputed").node();
// transform SVG to canvas using external canvg
canvg(canvasComputed, new XMLSerializer().serializeToString(svgCopyEl));
return canvasComputed;
}
.c3-chart-arc.c3-target text {
color: white;
fill: white;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.12/c3.min.css" rel="stylesheet" />
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.12/c3.min.js"></script>
<!-- Required to convert named colors to RGB -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvg/1.4/rgbcolor.min.js"></script>
<!-- Optional if you want blur -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/stackblur-canvas/1.4.1/stackblur.min.js"></script>
<!-- Main canvg code -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvg/1.5/canvg.js"></script>
<script src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>
SVG
</h4>
<div id="chart" class "c3">
</div>
<h4>
copy SVG
</h4>
<div id ="svgCopyEl">
</div>
<div>
<h4>
canvas
</h4>
<canvas id="canvasComputed"></canvas>
</div>
<button type="button" id="exportButton">
export to Canvas
</button>
Basically it was a combination of lack knowledge and a bug.
First of all, all relevant CSS styles have to be inlined when using canvg. Second, there was a bug in canvg using tspans and text-anchors.
Here is the (more or less) working code:
var columns = ['data11', 'data2', 'data347', 'data40098'];
var data = [150, 250, 300, 50];
var colors = ['#0065A3', '#767670', '#D73648', '#7FB2CE', '#00345B'];
var padding = 5;
/**
* global C3Styles object
*/
var C3Styles = null;
var legendData = [];
var sumTotal = 0
//prepare pie data
var columnData = [];
var columnNames = {};
for (i = 0; i < columns.length; i++) {
columnData.push([columns[i]].concat(data[i]));
var val = (Array.isArray(data[i])) ? data[i].reduce(function(pv, cv) {
return pv + cv;
}, 0) : data[i];
sumTotal += val;
legendData.push({
id: columns[i],
value: val,
ratio: 0.0
});
}
legendData.forEach(function(el, i) {
el.ratio = el.value / sumTotal
columnNames[el.id] = [el.id, d3.format(",.0f")(el.value), d3.format(",.1%")(el.ratio)].join(';');
});
var chart = c3.generate({
bindto: d3.select('#chart'),
data: {
columns: [
[columns[0]].concat(data[0])
],
names: columnNames,
type: 'pie',
},
legend: {
position: 'right',
show: true
},
pie: {
label: {
threshold: 0.001,
format: function(value, ratio, id) {
return [id, d3.format(",.0f")(value), "[" + d3.format(",.1%")(ratio) + "]"].join(';');
}
}
},
color: {
pattern: colors
},
onrendered: function() {
redrawLabelBackgrounds();
redrawLegend();
}
});
function addLabelBackground(index) {
/*d3.select('#chart').select("g.c3-target-" + columns[index].replace(/\W+/g, '-')+".c3-chart-arc")
.insert("rect", "text")
.style("fill", colors[index]);*/
var p = d3.select('#chart').select("g.c3-target-" + columns[index].replace(/\W+/g, '-') + ".c3-chart-arc");
var g = p.append("g");
g.append("rect")
.style("fill", colors[index]);
g.append(function() {
return p.select("text").remove().node();
});
}
for (var i = 0; i < columns.length; i++) {
if (i > 0) {
setTimeout(function(column) {
chart.load({
columns: [
columnData[column],
]
});
//chart.data.names(columnNames[column])
addLabelBackground(column);
}, (i * 5000 / columnData.length), i);
} else {
addLabelBackground(i);
}
}
function redrawLegend() {
d3.select('#chart').selectAll(".c3-legend-item > text").each(function() {
// get d3 node
var legendItem = d3.select(this);
var legendItemNode = legendItem.node();
//check if label is drawn
if (legendItemNode) {
if (legendItemNode.childElementCount === 0 && legendItemNode.innerHTML.length > 0) {
//build data
var data = legendItemNode.innerHTML.split(';');
legendItem.text("");
//TODO format legend dynamically depending on text
legendItem.append("tspan")
.text(data[0] + ": ")
.attr("class", "id-row")
.attr("text-anchor", "start");
legendItem.append("tspan")
.text(data[1] + " = ")
.attr("class", "value-row")
.attr("x", 160)
.attr("text-anchor", "end");
legendItem.append("tspan")
.text(data[2])
.attr("class", "ratio-row")
.attr("x", 190)
.attr("text-anchor", "end");
}
}
});
d3.select('#chart').selectAll(".c3-legend-item > rect").each(function() {
var legendItem = d3.select(this);
legendItem.attr("width", 190);
});
}
function redrawLabelBackgrounds() {
//for all label texts drawn yet
//for all label texts drawn yet
d3.select('#chart').selectAll(".c3-chart-arc > g > text").each(function(v) {
// get d3 node
var label = d3.select(this);
var labelNode = label.node();
//check if label is drawn
if (labelNode) {
var bbox = labelNode.getBBox();
var labelTextHeight = bbox.height;
if (labelNode.childElementCount === 0 && labelNode.innerHTML.length > 0) {
//build data
var data = labelNode.innerHTML.split(';');
label.html('')
.attr("dominant-baseline", "central")
.attr("text-anchor", "middle");
data.forEach(function(i, n) {
label.append("tspan")
.text(i)
.attr("dy", (n === 0) ? 0 : "1.2em")
.attr("x", 0);
}, label);
}
//check if element is visible
if (d3.select(labelNode.parentNode).style("display") !== 'none') {
//get pos of the label text
var pos = label.attr("transform").match(/-?\d+(\.\d+)?/g);
if (pos) {
// TODO: mofify the pos of the text
// pos[0] = (pos[0]/h*90000);
// pos[1] = (pos[1]/h*90000);
// remove dy and move label
//d3.select(this).attr("dy", 0);
//d3.select(this).attr("transform", "translate(" + pos[0] + "," + pos[1] + ")");
//get surrounding box of the label
bbox = labelNode.getBBox();
//now draw and move the rects
d3.select(labelNode.parentNode).select("rect")
.attr("transform", "translate(" + (pos[0] - bbox.width / 2 - padding) +
"," + (pos[1] - labelTextHeight/2 - padding)+")")
.attr("width", bbox.width + 2*padding)
.attr("height", bbox.height + 2*padding);
}
}
}
});
}
document.getElementById("exportButton").onclick = function() {
exportChartToImage();
};
function exportChartToImage() {
var createImagePromise = new Promise(function(resolve, reject) {
var images = [];
d3.selectAll('svg').each(function() {
if (this.parentNode) {
images.push(getSvgImage(this.parentNode, true));
}
});
if (images.length > 0)
resolve(images);
else
reject(images);
});
createImagePromise.then(function(images) {
/*images.forEach(function(img, n) {
img.toBlob(function(blob) {
saveAs(blob, "image_" + (n + 1) + ".png");
});
});*/
})
.catch(function(error) {
throw error;
});
};
/**
* Converts a SVG-Chart to a canvas and returns it.
*/
function getSvgImage(svgContainer) {
var svgEl = d3.select(svgContainer).select('svg').node();
var svgCopyEl = svgEl.cloneNode(true);
if (!svgCopyEl)
return;
d3.select("#svgCopyEl").selectAll("*").remove();
d3.select("#svgCopyEl").node().append(svgCopyEl); //.transition().duration(0);
//apply C3 CSS styles to SVG
// SVG doesn't use CSS visibility and opacity is an attribute, not a style property. Change hidden stuff to "display: none"
d3.select("#svgCopyEl").selectAll('*')
.filter(function(d) {
return d && d.style && (d.style('visibility') === 'hidden' || d.style('opacity') === '0');
})
.style('display', 'none');
d3.select("#svgCopyEl").selectAll('.c3-chart path')
.filter(function(d) {
return d && d.style('fill') === 'none';
})
.attr('fill', 'none');
d3.select("#svgCopyEl").selectAll('.c3-chart path')
.filter(function(d) {
return d && d.style('fill') !== 'none';
})
.attr('fill', function(d) {
return d.style('fill');
});
//set c3 default font
d3.select("#svgCopyEl").selectAll('.c3 svg')
.style('font', 'sans-serif')
.style('font-size', '10px');
//set c3 legend font
d3.select("#svgCopyEl").selectAll('.c3-legend-item > text')
.style('font', 'sans-serif')
.style('font-size', '12px');
d3.select("#svgCopyEl").selectAll('.c3-legend-item > text > tspan')
.style('font', 'sans-serif')
.style('font-size', '12px');
//set c3 arc shapes
d3.select("#svgCopyEl").selectAll('.c3-chart-arc path,rect')
.style('stroke', '#fff');
d3.select("#svgCopyEl").selectAll('.c3-chart-arc text')
.attr('fill', '#fff')
.style('font', 'sans-serif')
.style('font-size', '13px');
//fix weird back fill
d3.select("#svgCopyEl").selectAll("path").attr("fill", "none");
//fix no axes
d3.select("#svgCopyEl").selectAll("path.domain").attr("stroke", "black");
//fix no tick
d3.select("#svgCopyEl").selectAll(".tick line").attr("stroke", "black");
var canvasComputed = d3.select("#canvasComputed").node();
// transform SVG to canvas using external canvg
canvg(canvasComputed, new XMLSerializer().serializeToString(svgCopyEl));
return canvasComputed;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.12/c3.min.css" rel="stylesheet" />
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.12/c3.min.js"></script> -->
<!-- Required to convert named colors to RGB -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvg/1.4/rgbcolor.min.js"></script>
<!-- Optional if you want blur -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/stackblur-canvas/1.4.1/stackblur.min.js"></script>
<!-- Main canvg code -->
<script src="https://cdn.jsdelivr.net/npm/canvg#2.0.0-beta.1/dist/browser/canvg.min.js"></script>
<script src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>
SVG
</h4>
<div id="chart" class "c3">
</div>
<h4>
copy SVG
</h4>
<div id="svgCopyEl">
</div>
<div>
<h4>
canvas
</h4>
<canvas id="canvasComputed"></canvas>
</div>
<button type="button" id="exportButton">
export to Canvas
</button>

How can I display tooltips from multiple maps when mousover on one of the maps in D3js

I have a dashboard with two separate maps of a state showing different data based on years 2014 and 2012. The map when hovered over show the name of area individually. What I need to do is display both 2012 and 2014 maps's tooltips at the same time over the respective maps when I mouseover any one of the two maps. How can I display both at the same time. I would appreciate any help with this. Thanks.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test dashboard</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" >
<style>
#gujarat-viz-2017, #buttons {
border-right: 1px solid #ccc
}
.container {
background-color: #d5e8ec;
}
.const0 {
display: none;
}
.emptyparty {
fill:#f9f9f1;
}
.emptyparty:hover, .constituency:hover {
fill:#ccc;
}
.hidden { display: none; }
.showtooltip { position: absolute; z-index: 10000; background-color: #333;
border-radius: 10px; color: #fff; padding: 5px; }
/*Party colors*/
.bjp{ fill: #f88101;}
.inc{ fill: #6da736;}
.ncp{ fill: #076598;}
.gpp{ fill: #5a469d;}
.ind{ fill: #25a29a;}
.jdu{ fill: #eb4d4c;}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div id="gujarat-viz-2014" class="col-md-6">
<h2>2014</h2>
</div>
<div id="gujarat-viz-2012" class="col-md-6">
<h2>2012</h2>
</div>
</div> <!-- .row -->
</div>
<script src="http://www.thehindu.com/static/js/jquery-1.10.2.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script>
function map_function(map_settings){
// Global variables
var margin = { top: 50, left:50, right:50, bottom:50 },
height = 400 - margin.top - margin.bottom,
width = 500 - margin.left - margin.right;
// Create SVG canvas with responsive resizing
var svg = d3.select(map_settings["htmlelement"])
.append("svg")
.attr("viewBox", "0 0 " + width + " " + height)
.attr("preserveAspectRatio", "xMinYMin")
.append("g")
.attr("class", "data"+map_settings["year"])
// Add a tooltip to visualization
var tooltip = d3.select('body').append('div')
.attr('class', 'hidden showtooltip')
.attr('id', "tooltip"+map_settings["year"])
// queue and read the topojson, json data file
d3.queue()
.defer(d3.json, "https://api.myjson.com/bins/17m3if")
.defer(d3.json, map_settings.data)
.await(render_map)
var projection = d3.geoMercator()
.scale(3000)
.center([71.5, 22.3])
.translate([width / 2, height / 2])
var geoPath = d3.geoPath()
.projection(projection)
function render_map(error, mapshape, mapdata){
var constituency = topojson.feature(mapshape, mapshape.objects.collection).features;
dataMap = {};
mapdata.forEach(function(d){
dataMap[d.constNo] = d;
})
var fill_function = function(d) {
// d3.select(this).attr('fill', "white")
} // end of mousemove_function
var mousemove_function = function(d) {
var constinfo = dataMap[d.properties.AC_NO];
// console.log(constinfo.constituencyName)
// console.log(d3.select(this).data()[0].properties)
var html = "<p>"+constinfo.constituencyName+"</p>"
tooltip.classed('hidden', false)
.html(html)
.style("left", (d3.event.clientX - 10) + "px")
.style("top", (d3.event.clientY - 45) + "px");
} // end of mousemove_function
var class_function = function(d) {
var constinfo = dataMap[d.properties.AC_NO];
var className = "constituency ";
if(constinfo !== undefined) {
className += ("c"+constinfo.constNo+" ")
className += constinfo.leadingParty.replace(/[^a-zA-Z ]/g, "").toLowerCase()
} else {
className += "emptyparty"
className += " const"
className += d.properties.AC_NO
}
return className;
} // end of class_function
var mouseout_function = function(d) {
tooltip.classed('hidden', true)
} // end of mousemove_function
svg.selectAll(".constituency")
.data(constituency)
.enter().append("path")
.attr("d", geoPath)
.attr('class', class_function)
.attr('fill', "white")
.attr('stroke', "#e8e8e8")
.attr('stroke-width', "0.5")
.on('mouseover', mousemove_function)
.on('mouseout', mouseout_function)
} // render_map
} // map_function
var gujarat_data_2014 = {
htmlelement: "#gujarat-viz-2014",
data: "https://api.myjson.com/bins/yolfr",
year: "2014"
};
var gujarat_data_2012 = {
htmlelement: "#gujarat-viz-2012",
data: "https://api.myjson.com/bins/19ztxj",
year: "2012"
};
map_function(gujarat_data_2014);
map_function(gujarat_data_2012);
</script>
</body>
</html>
I'd modify your mousemove and mouseout to operate on both maps at the same time:
var mousemove_function = function(d) {
var constinfo = dataMap[d.properties.AC_NO];
var html = "<p>" + constinfo.constituencyName + "</p>"
var tooltips = d3.selectAll('.showtooltip');
// get paths from all maps
d3.selectAll('.c' + constinfo.constNo)
.each(function(d,i){
var pos = this.getBoundingClientRect();
// operate on appropriate tooltip
d3.select(tooltips.nodes()[i]).classed('hidden', false)
.html(html)
.style("left", (pos.x + pos.width/2) + "px")
.style("top", (pos.y - pos.height/2) + "px");
});
} // end of mousemove_function
var mouseout_function = function(d) {
d3.selectAll('.showtooltip').classed('hidden', true);
} // end of mousemove_function
Running code here.

Creating sunburst to accept csv data

I've maybe tried to run before I can walk but I've used the following two references:
http://codepen.io/anon/pen/fcBEe
https://bl.ocks.org/mbostock/4063423
From the first I've tried to take the idea of being able to feed a csv file into the sunburst with the function buildHierarchy(csv). The rest of the code is from Mike Bostock's example.
I've narrowed the data down to something very simple as follows:
var text =
"N-CB,50\n\
N-TrP-F,800\n";
So I thought this would produce three concentric rings - which is does - but I was hoping that the inner ring would be split in the ratio of 800:50 as in the data. Why am I getting the rings that I'm getting?
<!DOCTYPE html>
<meta charset="utf-8">
<style>
#sunBurst {
position: absolute;
top: 60px;
left: 20px;
width: 250px;
height: 300px;
}
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: auto;
position: relative;
width: 250px;
}
form {
position: absolute;
right: 20px;
top: 30px;
}
</style>
<form>
<label>
<input type="radio" name="mode" value="size" checked> Size</label>
<label>
<input type="radio" name="mode" value="count"> Count</label>
</form>
<script src="//d3js.org/d3.v3.min.js"></script>
<div id="sunBurst"></div>
<script>
var text =
"N-CB,50\n\
N-TrP-F,800\n";
var csv = d3.csv.parseRows(text);
var json = buildHierarchy(csv);
var width = 300,
height = 250,
radius = Math.min(width, height) / 2,
color = d3.scale.category20c();
//this bit is easy to understand:
var svg = d3.select("#sunBurst").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr({
'transform': "translate(" + width / 2 + "," + height * .52 + ")",
id: "sunGroup"
});
// it seems d3.layout.partition() can be either squares or arcs
var partition = d3.layout.partition()
.sort(null)
.size([2 * Math.PI, radius * radius])
.value(function(d) {
return 1;
});
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);
});
var path = svg.data([json]).selectAll("path")
.data(partition.nodes)
.enter()
.append("path")
.attr("display", function(d) {
return d.depth ? null : "none";
})
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d) {
return color((d.children ? d : d.parent).name);
})
.attr("fill-rule", "evenodd")
.style("opacity", 1)
.each(stash);
d3.selectAll("input").on("change", function change() {
var value = this.value === "size" ? function() {
return 1;
} : function(d) {
return d.size;
};
path
.data(partition.value(value).nodes)
.transition()
.duration(2500)
.attrTween("d", arcTween);
});
//});
// Stash the old values for transition.
function stash(d) {
d.x0 = d.x;
d.dx0 = d.dx;
}
// Interpolate the arcs in data space.
function arcTween(a) {
var i = d3.interpolate({
x: a.x0,
dx: a.dx0
}, a);
return function(t) {
var b = i(t);
a.x0 = b.x;
a.dx0 = b.dx;
return arc(b);
};
}
d3.select(self.frameElement).style("height", height + "px");
// 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;
};
</script>
There is a further live example of here on plunker : https://plnkr.co/edit/vqUqDtPCRiSDUIwfCbnY?p=preview
Your buildHierarchy function takes whitespace into account. So, when you write
var text =
"N-CB,50\n\
N-TrP-F,800\n";
it is actually two root nodes:
'N' and ' N'
You have two options:
Use non-whitespace text like
var text =
"N-CB,50\n" +
"N-TrP-F,800\n";
Fix buildHierarchy function to trim whitespace.

Displaying SVG elements with D3 and d3.slider: Uncaught ReferenceError: svg is not defined

Hey Im' currently experimenting with this D3 Example and I want to implement my own slider which is showing data of a json File (I included everything in a github repo because I don't know how to show you my working files and not spend to much space for it - especially the json file. Any tips for the future?). So basically I have my bubble.html:
<!DOCTYPE html>
<head>
<title>D3 Mapping Timeline</title>
<meta charset="utf-8">
<link rel="stylesheet" href="d3.slider.css" />
<style>
path {
fill: none;
stroke: #333;
stroke-width: .5px;
}
.land-boundary {
stroke-width: 1px;
}
.county-boundary {
stroke: #ddd;
}
.site {
stroke-width: .5px;
stroke: #333;
fill: #9cf;
}
#slider3 {
margin: 20px 0 10px 20px;
width: 900px;
}
</style>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="d3.slider.js"></script>
</head>
<body>
<div id="slider3"></div>
<script>
var width = 1240,
height = 720;
var projection = d3.geo.mercator()
.translate([width / 2, height / 2])
.scale((width - 1) / 2 / Math.PI);
d3.json("vorfaelle.json", function(error, data){
console.log(data.features[1].geometry.coordinates);
window.site_data = data;
});
var displaySites = function(data) {
var sites = svg.selectAll(".site")
.data(data);
sites.enter().append("circle")
.attr("class", "site")
.attr("cx", function(d) {
for (var i = 0; i < d.features.length+1; i++) {
console.log(d.features[i].geometry.coordinates[0]);
return projection(d.features[i].geometry.coordinates[0])
//return projection([d.lng, d.lat])[0];
}
})
.attr("cy", function(d) {
for (var i = 0; i < d.features.length+1; i++) {
console.log(d.features[i].geometry.coordinates[1]);
return projection([d.features[i].geometry.coordinates[1]])
//return projection([d.lng, d.lat])[0];
}
})
.attr("r", 1)
.transition().duration(400)
.attr("r", 5);
sites.exit()
.transition().duration(200)
.attr("r",1)
.remove();
};
// var minDateUnix = moment('2014-07-01', "YYYY MM DD").unix();
// var maxDateUnix = moment('2015-07-21', "YYYY MM DD").unix();
var dateParser = d3.time.format("%d.%m.%Y").parse;
var minDate = dateParser("01.01.2015");
var maxDate = dateParser("31.12.2015");
console.log(minDate);
var secondsInDay = 60 * 60 * 24;
d3.select('#slider3').call(d3.slider()
.axis(true).min(minDate).max(maxDate).step(1)
.on("slide", function(evt, value) {
var newData = _(site_data).filter( function(site) {
console.log(site)
// for (var i = 0; i < site.features.length; i++) {
// return site.features[i].properties.date < value;
// }
})
console.log("New set size ", newData.length);
displaySites(newData);
})
);
</script>
</body>
which is getting the data from the json (on my repo vorfaelle.json). Now when I move the slider handle it "crashes" and gives me this error:
What's exactly wrong? Is it because i did not read the data properly?
Add the svg element to the dom and assign it to a variable so that you can use it your code.
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);

how to put bird counts data in d3.js to draw bar-chart on google map

I am new to d3.js ,I made reference this example: http://bl.ocks.org/emeeks/4531633 .
I changed the example's map to Google map ,and want to use SVG to draw bar
chart on the Google map.
<!DOCTYPE html>
<title>test</title>
<meta charset="utf-8">
<style type="text/css">
.gmap{ display: block; width: 1000px; height: 800px; }
.stations, .stations svg { position: absolute; }
.stations svg { width: 120px; height: 30px; padding-right: 100px; font: 12px sans-serif; }
.stations circle { fill: yellow; stroke: black; stroke-width: 1.5px; }
</style>
<body>
<div class="gmap" id="map-canvas"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script></script>
<script>
var map;
function initialize() {
var mapOptions = { zoom: 8, center: new
google.maps.LatLng(23.7147979,120.7105502) };
map = new google.maps.Map( document.getElementById('map-canvas') , mapOptions);
}
initialize();
var width = 960, height = 960;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.csv("223-loc.csv", function(data) {
var parse = d3.time.format("%Y/%m/%d").parse;
aaa = d3.nest()
.key(function(d){ return d.birdName;})
.entries(stocks = data);
aaa_copy = d3.nest()
.key(function(d){ return d.birdName;})
.entries(stocks = data);
var position2keep= new Array();
var i=0;
aaa.forEach(function(s)
{
for (nn=0; nn<selectAryy.length; nn++)
{
if (s.key == selectAryy[nn])
{ position2keep.push(i); break; }
}
i++;
});
position2keep.sort();
for (j=aaa_copy.length-1; j>=0; j--)
{
if ( position2keep.indexOf(j) == -1)
aaa_copy.splice(j,1);
}
aaa_copy.forEach(function(s) {
s.values.forEach(function(d) {
for (nn=0; nn<selectAryy.length; nn++){
if (d.birdName== selectAryy[nn]){
d.date = parse(d.date);
d.count = +d.count;
d.lat = +d.lat;
d.lng = +d.lng;
}
}
bars = svg.selectAll("g")
.data(s)
.enter()
.append("g")
.attr("class", "bars")
.attr("transform", function(d) {return "translate("+ d.lat +","+
d.lng+")";});
bars.append("rect")
.attr('height', function(d) {return d.count*1000})
.attr('width', 10)
.attr('y', function(d) {return -(d.count)})
.attr("class", "bars")
.style("fill", "green");
bars.append("text")
.text(function(d) {return d.location})
.attr("x", -10)
.attr("y", 18);
bars.setMap(map);
});
});
});
</script>
</body>
My CSV data: https://drive.google.com/open?id=0B6SUWnrBmDwSWkI4bVNtOTNSOTA
I use d3.csv load data,it works.
But When I want to put the data into SVG to draw bar chart,it didn't work.
Can anyone help me to fix it?
In the provided example there are some issues:
selectAryy is not defined
and most importantly bars.setMap(map); does not seem valid. Do you mean setMap function of google.maps.OverlayView object?
In order to create a bar chart on Google Maps i would recommend to implement it as Custom Overlay.
Having said that the below example demonstrates how to add svg objects (bar chart) into Google Maps using overlay technique:
Example
function BarChartOverlay(chartData, map){
this.map_ = map;
this.chartData_ = chartData;
this.div_=null;
this.setMap(map);
}
BarChartOverlay.prototype = new google.maps.OverlayView();
BarChartOverlay.prototype.onAdd = function(){
var overlayProjection = this.getProjection();
var div = document.createElement('div');
div.setAttribute('id','chartDiv');
var chartArea = d3.select(div).append("svg");
this.chartData_.forEach(function(item){
var pos = overlayProjection.fromLatLngToDivPixel(new google.maps.LatLng(item[0], item[1]));
var bar = chartArea
.append("rect")
.attr("x", pos.x)
.attr("y", pos.y)
.attr("width", 40)
.attr("height", item[2])
.attr("fill-opacity", '0.5')
.attr("fill", 'purple');
});
this.div_ = div;
this.chartArea_ = chartArea;
var panes = this.getPanes();
panes.overlayLayer.appendChild(div);
};
BarChartOverlay.prototype.draw = function(){
var overlayProjection = this.getProjection();
var sw = overlayProjection.fromLatLngToDivPixel(this.map_.getBounds().getSouthWest());
var ne = overlayProjection.fromLatLngToDivPixel(this.map_.getBounds().getNorthEast());
var chartAreaSize = sw.x + ' ' + ne.y + ' ' + (ne.x - sw.x) + ' ' + (sw.y - ne.y);
this.chartArea_.attr('viewBox',chartAreaSize);
};
BarChartOverlay.prototype.onRemove = function(){
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
};
function initialize() {
var mapOptions = {
zoom: 8, center: new
google.maps.LatLng(23.7147979, 120.7105502)
};
var chartData = [
[25.204757,121.6896172,100],
[22.7972447,121.0713702,130],
[24.254972,120.6011066,80]
];
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var overlay = new BarChartOverlay(chartData, map);
}
initialize();
.gmap {
display: block;
width: 1000px;
height: 800px;
}
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<div class="gmap" id="map-canvas"></div>

Categories

Resources