d3 donut chart update with new csv dataset - d3.js

Really struggling to get the donut chart updated with new data coming from several csv files.
How can I update the chart with the new csv file? Im using setInterval() to circulate the array of files.
My code:
var updateChart = function(){}
var width = 360;
var height = 360;
var radius = Math.min(width, height) / 2;
var donutWidth = 75;
var legendRectSize = 18;
var legendSpacing = 4;
var color = d3.scale.category20b();
var svg = d3.select('#chart')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + (width / 2) +
',' + (height / 2) + ')');
var arc = d3.svg.arc()
.innerRadius(radius - donutWidth)
.outerRadius(radius);
var pie = d3.layout.pie()
.value(function(d) { return d.population; })
.sort(null);
d3.csv('data.csv', function(error, dataset) {
dataset.forEach(function(d) {
d.population = +d.population;
}); /
var path = svg.selectAll('path')
.data(pie(dataset))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d, i) {
return color(d.data.age);
});
var legend = svg.selectAll('.legend')
.data(color.domain())
.enter()
.append('g')
.attr('class', 'legend')
.attr('transform', function(d, i) {
var height = legendRectSize + legendSpacing;
var offset = height * color.domain().length / 2;
var horz = -2 * legendRectSize;
var vert = i * height - offset;
return 'translate(' + horz + ',' + vert + ')';
});
legend.append('rect')
.attr('width', legendRectSize)
.attr('height', legendRectSize)
.style('fill', color)
.style('stroke', color);
legend.append('text')
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendRectSize - legendSpacing)
.text(function(d) { return d; });
});
THE CSV FORMAT:
age,population
Cumulative,2704659
Cumulative Prev,4499890

Related

How to add image at the end of Arc

I am using d3 js i have to show image at the end of the arc how can i achieve that below is my example
var total_codes = 8;
var remaining_codes = 4;
var issued = total_codes - remaining_codes;
var coloursArray = ["#128ED2", "#dadada"];
var dataset = {
privileges: [issued, remaining_codes]
};
var width = 160,
height = 160,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(coloursArray);
var pie = d3.layout.pie()
.sort(null);
var arc = d3.svg.arc()
.innerRadius(radius - 30)
.outerRadius(radius);
var svg = d3.select("#donut").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var path = svg.selectAll("path")
.data(pie(dataset.privileges))
.enter().append("path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc);
path.transition().duration(750);
var point = path.node().getPointAtLength(path.node().getTotalLength() / 2);
svg.append("image")
.attr("cx", point.x)
.attr("cy", point.y)
.attr({
"xlink:href": "http://run.plnkr.co/preview/ckf41wu0g00082c6g6bzer2cc/images/pacman_active_icon.png", //nothing visible
width: 35,
height: 36
});
svg.append("text")
.attr("dy", ".0em")
.style("text-anchor", "middle")
.attr("class", "inside")
.html(function() {
return "<tspan x='0' dy='0em'>External</tspan><tspan x='0' dy='1.2em'>Privileges</tspan>";
}); // Add your code here
<script src="https://d3js.org/d3.v3.min.js"></script>
<div id="donut"></div>
It's a bit tedious, but the following works.
You take the first element of pieData, which denotes the blue arc. Then calculate the offset to put the pacman in the right position, using trigonometry. Finally, first translate it so it rotates around its centre, then rotate it the required amount.
I placed it at radius - 15 from the centre, because that is the middle of the 30 pixel wide arc.
var total_codes = 8;
var remaining_codes = 5;
var issued = total_codes - remaining_codes;
var coloursArray = ["#128ED2", "#dadada"];
var dataset = {
privileges: [issued, remaining_codes]
};
var width = 160,
height = 160,
radius = Math.min(width, height) / 2,
iconSize = 48;
var color = d3.scale.ordinal()
.range(coloursArray);
var pie = d3.layout.pie()
.sort(null);
var arc = d3.svg.arc()
.innerRadius(radius - 30)
.outerRadius(radius);
var svg = d3.select("#donut").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var pieData = pie(dataset.privileges);
var path = svg.selectAll("path")
.data(pieData)
.enter().append("path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc);
path.transition().duration(750);
svg
.append('g')
.attr('class', 'pacmancontainer')
.style('transform', function() {
// the radius of the center of the arc, also the hypothenuse of a triangle
var meanRadius = radius - 15;
var angleRadians = pieData[0].endAngle - Math.PI / 2;
var xOffset = Math.cos(angleRadians) * meanRadius;
var yOffset = Math.sin(angleRadians) * meanRadius;
return " translate(" + xOffset + "px, " + yOffset + "px)";
})
.append("image")
.attr({
"xlink:href": "http://run.plnkr.co/preview/ckf41wu0g00082c6g6bzer2cc/images/pacman_active_icon.png", //nothing visible
width: iconSize,
height: iconSize
})
// Make sure the Pacman rotates around its center
.style('transform-origin', (iconSize / 2) + 'px ' + (iconSize / 2) + 'px')
.style('transform', function() {
var angleDegrees = pieData[0].endAngle / (2 * Math.PI) * 360;
return "translate(-" + (iconSize / 2) + "px, -" + (iconSize / 2) + "px) rotate(" + angleDegrees + "deg)";
});
svg.append("text")
.attr("dy", ".0em")
.style("text-anchor", "middle")
.attr("class", "inside")
.html(function() {
return "<tspan x='0' dy='0em'>External</tspan><tspan x='0' dy='1.2em'>Privileges</tspan>";
}); // Add your code here
<script src="https://d3js.org/d3.v3.min.js"></script>
<div id="donut"></div>

Change bar chart into pie chart

initiaa Bar chart
I want to convert this bar chart into pie chart. I have tried plaing around with the transition function and appending code. But it doesnot seem to work.
edited pen
Here's the code for my pie chart
var width = 150;
var height = 150;
var radius = Math.min(width, height) / 2;
var donutWidth = 75;
var legendRectSize = 18;
var legendSpacing = 4;
var color = d3.scale.category20b();
var svg = d3.select('#chart')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + (width / 2) +
',' + (height / 2) + ')');
var arc = d3.svg.arc()
.innerRadius(radius - donutWidth)
.outerRadius(radius);
var pie = d3.layout.pie()
.value(function (d) {
return d.count;
})
.sort(null);
var tooltip = d3.select('#chart')
.append('div')
.attr('class', 'tooltip');
tooltip.append('div')
.attr('class', 'label');
tooltip.append('div')
.attr('class', 'count');
tooltip.append('div')
.attr('class', 'percent');
//d3.csv('weekdays.csv', function (error, dataset) {
dataset.forEach(function (d) {
d.count = +d.count;
d.enabled = true; // NEW
});
var path = svg.selectAll('path')
.data(pie(dataset))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function (d, i) {
return color(d.data.label);
}) // UPDATED (removed semicolon)
.each(function (d) {
this._current = d;
}); // NEW
path.on('mouseover', function (d) {
var total = d3.sum(dataset.map(function (d) {
return (d.enabled) ? d.count : 0; // UPDATED
}));
var percent = Math.round(1000 * d.data.count / total) / 10;
tooltip.select('.label').html(d.data.label);
tooltip.select('.count').html(d.data.count);
tooltip.select('.percent').html(percent + '%');
tooltip.style('display', 'block');
});
path.on('mouseout', function () {
tooltip.style('display', 'none');
});
The data linkage seemd to be the issue. Everytime the console said invalid values.
Here;s the working fiddle
var data = [10,20,30,40,60, 80, 20, 50];
// the D3 bits...
var color = d3.scale.category10();
var width = 180;
var height = 180;
var pie = d3.layout.pie().sort(null);
var arc = d3.svg.arc()
.outerRadius(width / 2 * 0.9)
.innerRadius(width / 2 * 0.5);
var svg = d3.select(element[0]).append('svg')
.attr({width: width, height: height})
.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
// add the <path>s for each arc slice
svg.selectAll('path').data(pie(data)) // our data
.enter().append('path')
.style('stroke', 'white')
.attr('d', arc)
.attr('fill', function(d, i){ return color(i) });

How to select only x rows from a csv file for a pie chart

I have a CSV file containing a hundreds of lines here's a sample :
city.csv:
City,JanTemp,Lat,Long
Indianapolis IN,21,39.8,86.9
Des_Moines IA,11,41.8,93.6
Wichita KS,22,38.1,97.6
Louisville KY,27,39,86.5
New_Orleans LA,45,30.8,90.2
Portland ME,12,44.2,70.5
Baltimore MD,25,39.7,77.3
Boston MA,23,42.7,71.4
Detroit MI,21,43.1,83.9
Minneapolis MN,2,45.9,93.9
St_Louis MO,24,39.3,90.5
Helena MT,8,47.1,112.4
Omaha NE,13,41.9,96.1
Concord NH,11,43.5,71.9
Atlantic_City NJ,27,39.8,75.3
Albuquerque NM,24,35.1,106.7
Albany NY,14,42.6,73.7
New_York NY,27,40.8,74.6
What I want to do is create a pie chart representing JanTemp for every 10 rows.
Here's my initial code to create a pie chart for all the rows :
script:
<script>
var width = 500;
var height = 500;
var radius = Math.min(width, height) / 2;
var donutWidth = 120;
var legendRectSize = 18;
var legendSpacing = 4;
var color = d3.scale.category20();
var svg = d3.select('#chart')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + (width / 2) +
',' + (height / 2) + ')');
var arc = d3.svg.arc()
.innerRadius(radius - donutWidth)
.outerRadius(radius);
var pie = d3.layout.pie()
.value(function(d) { return d.JanTemp; })
.sort(null);
d3.csv('city.csv', function(error, dataset) {
dataset.forEach(function(d) {
d.JanTemp = +d.JanTemp;
});
var path = svg.selectAll('path')
.data(pie(dataset))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d, i) {
return color(d.data.City);
});
var legend = svg.selectAll('.legend')
.data(color.domain())
.enter()
.append('g')
.attr('class', 'legend')
.attr('transform', function(d, i) {
var height = legendRectSize + legendSpacing;
var offset = height * color.domain().length / 2;
var horz = -2 * legendRectSize;
var vert = i * height - offset;
return 'translate(' + horz + ',' + vert + ')';
});
legend.append('rect')
.attr('width', legendRectSize)
.attr('height', legendRectSize)
.style('fill', color)
.style('stroke', color);
legend.append('text')
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendRectSize - legendSpacing)
.text(function(d) { return d; });
});
</script>
The code is working yet the visualization is bad.
The question is : How can I create a pie chart for every 10 rows in the csv file ? (Where also, can I add the property to only get rows by 10 ?) Is it even possible ?
You have two ways to do this, the first is to simply repeat what you have already and create several SVGs, one for each piechart.
The second is a bit more elegant, and involves a single SVG controlled by D3.
You'll first need to reorder your data into chunks of 10:
function( alldata ) {
var dataDivide = [], i, chunk = 10;
for (i=0; i<alldata.length; i+=chunk)
{
dataDivide.push(alldata.slice(i, i+chunk));
}
}
You can now use D3 to divide up your SVG and then set the chunks to be your data for each piechart:
var svg.selectAll("g")
.data( dataDivide )
.enter()
.append("g")
// position the g, etc.
.selectAll('path')
.data( function(d) {
return pie(d); // d is a chunk
})
.enter()
.append('path')
// etc.

Adding a legend to a pie chart in D3js

I'm trying to plot a pie chart with a legend inside of it. And I got into troubles to get it plotted, since I get the errors abound undefined variables. I managed to draw the chart itself and the half of the legend, but not in the right colors, what should match the pie chart.
function drawPieChart(d3div, chart_data) {
// chart_data.data is a list of data elements.
// each should contain fields: val, col, name
d3div.html(""); // clear the div
var title = getopt(chart_data, 'title', '');
// desired width and height of chart
var w = getopt(chart_data, 'width', 300);
var h = getopt(chart_data, 'height', 300);
var pad = getopt(chart_data, 'pad', 50);
var textmargin = getopt(chart_data, 'textmargin', 20);
var r = Math.min(w, h) / 2 - pad; // radius of pie chart
var div = d3div.append('div');
if(title !== '') {
div.append('p').attr('class', 'pietitle').text(title);
}
var arc = d3.svg.arc()
.outerRadius(r)
.cornerRadius(20)
.innerRadius(150);
var arcLarge = d3.svg.arc()
.innerRadius(150)
.cornerRadius(20)
.outerRadius(r + 50);
var toggleArc = function(p){
p.state = !p.state;
var dest = p.state ? arcLarge : arc;
d3.select(this).select("path").transition()
.duration(160)
.attr("d", dest);};
var pie = d3.layout.pie()
.padAngle(.03)
.sort(null)
.value(function(d) { return d.val; });
var svg = d3.select("#piechart").append("svg")
.attr("width", w)
.attr("height", h)
.append("g")
.attr("transform", "translate(" + w / 2 + "," + h / 2 + ")");
var g = svg.selectAll(".arc")
.data(pie(chart_data.data))
.enter().append("g")
.attr("class", "arc")
.attr("stroke", "#999")
.attr("id",function(d){return d.data;})
.on("mouseover",toggleArc)
.on("mouseout",toggleArc);
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return d.data.col; });
var color = d3.scale.category20b();
var legendRectSize = 18;
var legendSpacing = 4;
// FROM here the code is not produced the desired result
var legend = svg.selectAll('.legend')
.data(chart_data.data)
.enter()
.append('g')
.attr('class', 'legend')
.attr("id",function(d){return d.data;})
.attr('transform', function(d, i) {
var height = legendRectSize + legendSpacing;
var offset = height * chart_data.data.length / 2;
var horz = -2 * legendRectSize;
var vert = i * height - offset;
return 'translate(' + horz + ',' + vert + ')';
});
legend.append('rect')
.data(chart_data.data)
.attr('width', legendRectSize)
.attr('height', legendRectSize)
.style("fill", function(d) { return d.data.col; });
legend.append("text")
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendRectSize - legendSpacing)
.text(function(d) { return d.data.name; });
}
The code actually works fine untill the line var legend = svg.selectAll('.legend')
Then i start to define the legend, but D3 complains about undefined d.data every time i try to access d.data below the line I written above(also in the last line of the code).
I don't understand where i got on the wrong way.
If instead of defining the whole non working part(var legend...) i write this code:
g.append("text")
.attr("stroke", "none")
.attr("fill", function(d) { return d.data.col; })
.text(function(d) { return d.data.name; });
I'm able to access the d.data.name.
Unfortunately wrong colors of the boxes and not description.
Thanks!

D3 Pie Error: Invalid value for <text> attribute transform="translate(NaN,NaN)"

Keep getting a console error of
Error: Invalid value for attribute transform="translate(NaN,NaN)"
Re-created the error here.
http://jsfiddle.net/9f9wonoc/
var width = 360;
var height = 360;
var radius = Math.min(width, height) / 2;
var color = {
'Pass': '#66B51B',
'Fail': '#d03324'
}
var data = [
{ label: 'Pass', count: 12 },
{ label: 'Fail', count: 10 },
];
var svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + (width / 2) + ',' + (height / 2) + ')');
var arc = d3.svg.arc()
.outerRadius(radius);
var pie = d3.layout.pie()
.value(function(d) { return d.count; })
.sort(null);
var path = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
path.append("path")
.attr("d", arc)
.style("fill", function(d) { return color[d.data.label]; });
path.append("text")
.attr("transform", function(d, i) {
return "translate(" + arc.centroid(d, i) + ")";
})
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.count; });
What am I doing wrong?
You missed one small thing :
you need to set the inner radius 0 as below:
var arc = d3.svg.arc()
.outerRadius(radius).innerRadius(0);
Working code here
Hope this helps!

Resources