Skip to content

Instantly share code, notes, and snippets.

@charlesdguthrie
Last active March 27, 2019 19:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save charlesdguthrie/11356441 to your computer and use it in GitHub Desktop.
Save charlesdguthrie/11356441 to your computer and use it in GitHub Desktop.
Live-Updating Bar Chart

A bar chart that updates live with new incoming data

[
{"key":"Obama Spends Another Night Searching Behind White House Paintings For Safes", "value":99},
{"key":"Report: Average American Consuming 4 Ounces Of Cheese Right Now", "value":78},
{"key":"Colorado Legalizes Medicinal Fireworks", "value":77},
{"key":"15-Second Meals", "value":64},
{"key":"Statshot: Why Aren't We Going To Prom?", "value":35},
{"key":"Report: U.S. Still Leads World With Highest Density Of Kevins", "value":33},
{"key":"Xylophonist Shredding It", "value":29},
{"key":"Man Has Story For Every Stain On Pants", "value":28},
{"key":"Music Playing In Bar Could Stand To Be Louder, Worse", "value":25},
{"key":"Grandfathers Accidentally Switched At Hospital", "value":21},
{"key":"Visit Home Referred To As Vacation By Parents", "value":19},
{"key":"Area Man Cleans Apartment Once Every Relationship", "value":18},
{"key":"Horoscopes", "value":15},
{"key":"White Male Privilege Squandered On Job At Best Buy", "value":14},
{"key":"Something Happens in Ukraine", "value":11}
]
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="everything">
<h1>What People Are Reading Right Now (Fake Data)</h1>
<h2>Top 10 Articles by Concurrent Page Views</h2>
<div id="chart"></div>
<h2>Headlines borrowed from <a href="http://www.theonion.com/">theonion.com</a></h2>
</div>
<script>
//updatingBarChart.js
var setup = function(targetID){
//Set size of svg element and chart
var margin = {top: 0, right: 0, bottom: 0, left: 0},
width = 600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom,
categoryIndent = 4*15 + 5,
defaultBarWidth = 2000;
//Set up scales
var x = d3.scale.linear()
.domain([0,defaultBarWidth])
.range([0,width]);
var y = d3.scale.ordinal()
.rangeRoundBands([0, height], 0.1, 0);
//Create SVG element
d3.select(targetID).selectAll("svg").remove()
var svg = d3.select(targetID).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//Package and export settings
var settings = {
margin:margin, width:width, height:height, categoryIndent:categoryIndent,
svg:svg, x:x, y:y
}
return settings;
}
var redrawChart = function(targetID, newdata) {
//Import settings
var margin=settings.margin, width=settings.width, height=settings.height, categoryIndent=settings.categoryIndent,
svg=settings.svg, x=settings.x, y=settings.y;
//Reset domains
y.domain(newdata.sort(function(a,b){
return b.value - a.value;
})
.map(function(d) { return d.key; }));
var barmax = d3.max(newdata, function(e) {
return e.value;
});
x.domain([0,barmax]);
/////////
//ENTER//
/////////
//Bind new data to chart rows
//Create chart row and move to below the bottom of the chart
var chartRow = svg.selectAll("g.chartRow")
.data(newdata, function(d){ return d.key});
var newRow = chartRow
.enter()
.append("g")
.attr("class", "chartRow")
.attr("transform", "translate(0," + height + margin.top + margin.bottom + ")");
//Add rectangles
newRow.insert("rect")
.attr("class","bar")
.attr("x", 0)
.attr("opacity",0)
.attr("height", y.rangeBand())
.attr("width", function(d) { return x(d.value);})
//Add value labels
newRow.append("text")
.attr("class","label")
.attr("y", y.rangeBand()/2)
.attr("x",0)
.attr("opacity",0)
.attr("dy",".35em")
.attr("dx","0.5em")
.text(function(d){return d.value;});
//Add Headlines
newRow.append("text")
.attr("class","category")
.attr("text-overflow","ellipsis")
.attr("y", y.rangeBand()/2)
.attr("x",categoryIndent)
.attr("opacity",0)
.attr("dy",".35em")
.attr("dx","0.5em")
.text(function(d){return d.key});
//////////
//UPDATE//
//////////
//Update bar widths
chartRow.select(".bar").transition()
.duration(300)
.attr("width", function(d) { return x(d.value);})
.attr("opacity",1);
//Update data labels
chartRow.select(".label").transition()
.duration(300)
.attr("opacity",1)
.tween("text", function(d) {
var i = d3.interpolate(+this.textContent.replace(/\,/g,''), +d.value);
return function(t) {
this.textContent = Math.round(i(t));
};
});
//Fade in categories
chartRow.select(".category").transition()
.duration(300)
.attr("opacity",1);
////////
//EXIT//
////////
//Fade out and remove exit elements
chartRow.exit().transition()
.style("opacity","0")
.attr("transform", "translate(0," + (height + margin.top + margin.bottom) + ")")
.remove();
////////////////
//REORDER ROWS//
////////////////
var delay = function(d, i) { return 200 + i * 30; };
chartRow.transition()
.delay(delay)
.duration(900)
.attr("transform", function(d){ return "translate(0," + y(d.key) + ")"; });
};
//Pulls data
//Since our data is fake, adds some random changes to simulate a data stream.
//Uses a callback because d3.json loading is asynchronous
var pullData = function(settings,callback){
d3.json("fakeData.json", function (err, data){
if (err) return console.warn(err);
var newData = data;
data.forEach(function(d,i){
var newValue = d.value + Math.floor((Math.random()*10) - 5)
newData[i].value = newValue <= 0 ? 10 : newValue
})
newData = formatData(newData);
callback(settings,newData);
})
}
//Sort data in descending order and take the top 10 values
var formatData = function(data){
return data.sort(function (a, b) {
return b.value - a.value;
})
.slice(0, 10);
}
//I like to call it what it does
var redraw = function(settings){
pullData(settings,redrawChart)
}
//setup (includes first draw)
var settings = setup('#chart');
redraw(settings)
//Repeat every 3 seconds
setInterval(function(){
redraw(settings)
}, 3000);
</script>
</body>
MIT License
Copyright (c) 2019 Charlie Guthrie
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font: inherit;
font-size: 100%;
vertical-align: baseline;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: inherit;
}
h1 {
font-size:150%;
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: 300;
text-align: left;
margin-top: 5px;
margin-bottom: 5px;
}
h2 {
font-size: 12px;
font-style: italic;
color: gray;
margin-top:5px;
margin-bottom:5px;
}
#everything{
width:600px;
margin:20px;
}
#chart{
width:600px;
height:400px;
}
.bar{
fill:#eaeaea;
}
text.label{
fill: #777777;
color: #777777;
font-size: 20px;
font-weight: bold;
}
text.category{
fill: #666666;
font-size: 14px;
}
@Prabingiri
Copy link

WOW, thank you very much for such a wonderful project. Helped a lot. But, I got you a question. While I tried to replace the "fakeData.json" "fakedata.php", I am not getting anything in the output. What's my problem, have you tried it man? All I want is to retrieve the data from mysql but it is not working. By the way, If I copied the Json output of PHP to the data file, It works fine. But giving the direct file name produces no result. Help me out man.

@charlesdguthrie
Copy link
Author

Hi @Prabingiri, I'm sorry I never responded; I didn't see your note. The code is designed to take in .json format data, not php. Can you put your data into json format and save as a .json file?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment