Skip to content

Instantly share code, notes, and snippets.

@HarryStevens
Last active Oct 31, 2016
Embed
What would you like to do?
Bar Chart with "Popout" - Google Charts API
license: gpl-3.0

D3 is better than the Google Charts API in almost every way. But for Javascript beginners struggling with D3, the Google Charts API can be a reasonable alternative, with lots of out-of-the-box features that D3 does not provide.

Here is a simple bar chart with visual "popout" and annotations rendered with the Google Charts API.

var json = [
{
"name": "Andrew",
"value": 95.77,
"category": "A"
},
{
"name": "Matthew",
"value": 103.62,
"category": "A"
},
{
"name": "Mark",
"value": 94.2,
"category": "A"
},
{
"name": "Luke",
"value": 91.06,
"category": "A"
},
{
"name": "John",
"value": 76.93,
"category": "A"
},
{
"name": "Jimmy",
"value": 65.94,
"category": "B"
},
{
"name": "Bill",
"value": 64.37,
"category": "A"
},
{
"name": "Bob",
"value": 54.95,
"category": "A"
},
{
"name": "Kate",
"value": 74.93,
"category": "A"
},
{
"name": "Alice",
"value": 35.13,
"category": "A"
},
{
"name": "Sally",
"value": 85.74,
"category": "B"
},
{
"name": "Mary",
"value": 25.83,
"category": "B"
},
{
"name": "Jenny",
"value": 23.65,
"category": "A"
},
{
"name": "Barbara",
"value": 13.05,
"category": "A"
}
];
<html>
<head>
<style>
body {
margin: 0 auto;
display: table;
}
#chart {
width: 607.141px;
height: 300px;
}
</style>
</head>
<body>
<div id="chart"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="data.js"></script>
<script src="scripts.js"></script>
</body>
</html>
json.sort(function(a,b){
return b.value - a.value;
});
var dataArray = [];
var headers = ['Name', 'Value', {role: 'style'}, {role: 'annotation'}]
dataArray.push(headers);
json.forEach(function(d,i){
d.category === 'A' ? fill = '#CCC' : fill = '#B44682';
i === 0 || i === json.length - 1 ? annotation = d.value : annotation = null;
dataArray.push([d.name, d.value, fill, annotation]);
});
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(dataArray);
var options = {
chartArea: {
top: 10,
bottom: 0,
left: 65,
right: 50
},
hAxis: {
gridlines: {
color: '#fff'
}
},
legend: 'none',
vAxis: {
textStyle: {
fontName: 'Helvetica Neue',
fontSize: 14
}
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart'));
chart.draw(data, options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment