Skip to content

Instantly share code, notes, and snippets.

@wheresjames
Last active November 14, 2016 19:17
Show Gist options
  • Save wheresjames/07673e69bd1d1c23202de5cd2e7dcca2 to your computer and use it in GitHub Desktop.
Save wheresjames/07673e69bd1d1c23202de5cd2e7dcca2 to your computer and use it in GitHub Desktop.
Dynamic C3 Donut Chart
<!DOCTYPE html>
<meta charset="utf-8">
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.11/c3.min.css" rel="stylesheet">
<style>
body
{
min-width: 800px;
}
.chart
{
width: 600px;
height: 400px;
margin: 1em;
padding: 1em;
border: 2px dashed #888;
background: #ccc;
}
</style>
<body>
<div id="chart" class="chart"></div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.11/c3.js"></script>
<script>
var chart = c3.generate({
bindto: '#chart',
data: {
columns: [
['Data1', 100]
],
type : 'donut',
}
});
d3.select(window).on( "resize", function() { chart.resize(); } );
var used = [];
function update()
{
var cols = [];
var offset = parseInt( Math.random() * 10 );
// Create new data
for (var i = 0; i < 10; i++)
cols.push( [ 'Data'+(offset + i), parseInt( Math.random() * 1000 ) ] );
// Create an array of old keys
var nkeys = cols.reduce(function(p, c){ p.push(c[0]); return p; }, []);
var remove = used.filter(function(v){ return nkeys.indexOf(v) < 0;});
used = nkeys;
// Load the new data
chart.load({columns: cols, unload: remove});
setTimeout(update, 1000);
}
$(update);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment