Google chart y axis customization - javascript

How can I show star image OR star glyphicon with each Y-axis number. For example, in the bar chart, it will be like *5. So star image will be with each number.
JS code
google.charts.load("current", {packages: ["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var five = parseInt($("#fivestar").val());
var four = parseInt($("#fourstar").val());
var three = parseInt($("#threestar").val());
var two = parseInt($("#twostar").val());
var one = parseInt($("#onestar").val());
var data = google.visualization.arrayToDataTable([
["Element", "Stars", {role: "style"}],
["5", five, "#4F9808"],
["4", four, "#C4C62F"],
["3", three, "#E4C10D"],
["2", two, "color: #F6D219"]
]);
data.addRows([
["1", one, "color: #CA5006"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"},
2]);
var options = {
title: "Total Ratings",
width: 400,
height: 358,
bar: {groupWidth: "60%"},
chartArea: {top:10,left:30,width: '50%', height: '50%'},
legend: {position: "none"},
};
var chart = new google.visualization.BarChart(document.getElementById("chart_div"));
chart.draw(view, options);
}
I tried to add star in the code like this
var data = google.visualization.arrayToDataTable([
["Element", "Stars", {role: "style"}],
["<div class="star"><i class="fa fa-star" aria-hidden="true"></i></div>5", five, "#4F9808"],
["<div class="star"><i class="fa fa-star" aria-hidden="true"></i></div>4", four, "#C4C62F"],
["<div class="star"><i class="fa fa-star" aria-hidden="true"></i></div>3", three, "#E4C10D"],
["<div class="star"><i class="fa fa-star" aria-hidden="true"></i></div>2", two, "color: #F6D219"]
]);
BUT it is not working..it is just printing the html tags as string.
Any help is much appreciated..

one way, would be to manually add and position the star elements,
based on the y attribute of the Y-axis labels,
which can be determined when the chart's 'ready' event fires
see following working snippet...
google.charts.load("current", {packages: ["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var colors = ["#4F9808", "#C4C62F", "#E4C10D", "#F6D219", "#CA5006"];
var five = parseInt(1);
var four = parseInt(1);
var three = parseInt(2);
var two = parseInt(1);
var one = parseInt(1);
var data = google.visualization.arrayToDataTable([
["Element", "Stars", {role: "style"}],
["5", five, colors[0]],
["4", four, colors[1]],
["3", three, colors[2]],
["2", two, colors[3]]
]);
data.addRows([
["1", one, colors[4]]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"},
2]);
var options = {
title: "Total Ratings",
width: 400,
height: 358,
bar: {groupWidth: "60%"},
chartArea: {top:10,left:30,width: '50%', height: '50%'},
legend: {position: "none"},
};
var container = document.getElementById("chart_div");
var chart = new google.visualization.BarChart(container);
// add stars
google.visualization.events.addListener(chart, 'ready', function () {
var colorIndex = 0;
Array.prototype.forEach.call(container.getElementsByTagName('text'), function(text) {
if ((text.getAttribute('text-anchor') === 'end') &&
(text.getAttribute('fill') === '#222222')) {
var stars = document.getElementById("star_div");
var star = stars.appendChild(document.createElement('i'));
star.className = "fa fa-star star";
star.style.color = colors[colorIndex];
star.style.top = (parseFloat(text.getAttribute('y'))) + 'px';
colorIndex++;
}
});
});
chart.draw(view, options);
}
.ratings {
display: inline-block;
padding: 6px;
text-align: right;
vertical-align: top;
}
.star {
position: absolute;
}
#star_div {
width: 16px;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<div>
<div class="ratings" id="star_div"></div>
<div class="ratings" id="chart_div"></div>
</div>

Related

Why does Google Chart increase my page width?

I create a Google charts, in php page
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:['corechart']});</script>
<script type="text/javascript">
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["M", "COUNT",{ role: 'style' }],
var view = new google.visualization.DataView(data);
var options = {
width: 200,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart1 = new google.visualization.ColumnChart(document.getElementById("columnchart_values1"));
chart1.draw(view, options);
document.getElementById("columnchart_values1").style.display = "block";
}
</script>
<div style="width:80%;"class="columnchart_values" id="columnchart_values1"> </div>
The graph is fine, but the page width varies - very large. Why?
enter image description here

How to add a total to a chart in google charts

I would like to add a total of the amounts to the chart below.
https://jsfiddle.net/porterhouse47/6e0ejxLb/
I created a function to sum the values and you can see that it's correct if you uncomment the alert. I tried adding a new row for the total as you can see at the bottom but it doesn't show.
// Load Charts and the corechart/bar char package.
google.charts.load('current', {
packages: ['corechart']
});
// Draw the pie chart for the Total Costs when Charts is loaded.
google.charts.setOnLoadCallback(drawPieChart);
// Draw the pie
function drawPieChart() {
var data = google.visualization.arrayToDataTable([
['Country', 'Dollars'],
['Canada', 12250000],
['USA', 22750000]
]);
function getSum(data, column) {
var total = 0;
for (i = 0; i < data.getNumberOfRows(); i++)
total = total + data.getValue(i, column);
return total;
}
//alert(getSum(data, 1));
// In order to show currency correctly
var formatter = new google.visualization.NumberFormat({
negativeColor: 'red',
negativeParens: true,
pattern: '$###,###'
});
formatter.format(data, 1);
var options = {
title: "North America 2017",
legend: {
position: 'top'
},
pieSliceText: 'value-and-percentage',
slices: {
0: {
color: '#328213'
},
1: {
offset: 0.1,
color: '#57a33a'
},
},
pieStartAngle: 70,
width: 400,
height: 300
};
var chart = new google.visualization.PieChart(document.getElementById('total_costs_pie'));
chart.draw(data, options);
addRow('Total', getSum(data, 1));
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
</script>
<body>
<!--Table and divs that hold the pie charts-->
<table class="columns">
<tr>
<td>
<div id="total_costs_pie" style="border: 1px solid #ccc"></div>
</td>
</tr>
</table>
Hi i have maby solution for you:
HTML:
</script>
<body>
<!--Table and divs that hold the pie charts-->
<table class="columns">
<tr>
<td>
<div id="total_costs_pie" style="border: 1px solid #ccc"></div>
</td>
</tr>
<tr>
<td id="total"></td>
<td id="number"></td>
</tr>
</table>
JAVASCRIPT:
// Load Charts and the corechart/bar char package.
google.charts.load('current', {
packages: ['corechart']
});
// Draw the pie chart for the Total Costs when Charts is loaded.
google.charts.setOnLoadCallback(drawPieChart);
// Draw the pie
function drawPieChart() {
var data = google.visualization.arrayToDataTable([
['Country', 'Dollars'],
['Canada', 12250000],
['USA', 22750000]
]);
function getSum(data, column) {
var total = 0;
for (i = 0; i < data.getNumberOfRows(); i++)
total = total + data.getValue(i, column);
return total;
}
//alert(getSum(data, 1));
// In order to show currency correctly
var formatter = new google.visualization.NumberFormat({
negativeColor: 'red',
negativeParens: true,
pattern: '$###,###'
});
formatter.format(data, 1);
var options = {
title: "North America 2017",
legend: {
position: 'top'
},
pieSliceText: 'value-and-percentage',
slices: {
0: {
color: '#328213'
},
1: {
offset: 0.1,
color: '#57a33a'
},
},
pieStartAngle: 70,
width: 400,
height: 300
};
var chart = new google.visualization.PieChart(document.getElementById('total_costs_pie'));
chart.draw(data, options);
//function for addRow.....
function addRow (name, number) {
//add name and number to .total
total_name = document.createTextNode(name + number);
total.appendChild(total_name);
}
addRow('Total: ', getSum(data, 1));
}
i added function for your addRow. And new tr and td to embed this atributes. I hope thats help you or give you path to do something like this ;)

Gauges Charts - multiple gauges java

I'm using Google Charts and I'm trying to add multiple charts to one json call.
The chart style is gauge.
The example below works for only one gauge "field1" I'm not that great with the charts but I did create a working example that updates.
What I want to add is two more gauges and the json array names would be Tlak,Vlhkost. So the json would look something like this {"created_at":"2017-04-19T17:05:54Z","entry_id":4381,"field1":"1.00\r\n\r\n","field2":"83"}
How would I go about adding one more gauges?
<html>
<head>
<title>Google Gauge - ThingSpeak</title>
</head>
<body>
<div id="container">
<div id="inner">
<div id="gauge_div"></div>
</div>
</div>
</body>
</html>
//css
<style type="text/css">
body { background-color: #FFFFFF; }
#container { height: 100%; width: 100%; }
#inner { }
#gauge_div { margin: 0 auto; }
</style>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
// set your channel id here
var channel_id = 248987;
// set your channel's read api key here if necessary
var api_key = '16UK5LLONGR9LCR2';
// maximum value for the gauge
var max_gauge_value = 1023;
// name of the gauge
var gauge_name = 'Tlak';
// global variables
var chart, charts, data;
// load the google gauge visualization
google.load('visualization', '1', {packages:['gauge']});
google.setOnLoadCallback(initChart);
// display the data
function displayData(point) {
data.setValue(0, 0, gauge_name);
data.setValue(0, 1, point);
chart.draw(data, options);
}
// load the data
function loadData() {
// variable for the data point
var p;
// get the data from thingspeak
$.getJSON('https://api.thingspeak.com/channels/' + channel_id + '/feed/last.json?api_key=' + api_key, function(data) {
// get the data point
p = data.field1;
// if there is a data point display it
if (p) {
// p = Math.round((p / max_gauge_value) * 100);
displayData(p);
}
});
}
// initialize the chart
function initChart() {
data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
data.addRows(1);
chart = new google.visualization.Gauge(document.getElementById('gauge_div'));
options = {
width: 160, height: 160, min: 955, max: 1065,
majorTicks: [950, 980, 1010, 1040, 1060], minorTicks: 10,
greenFrom: 955,
greenTo: 1000,
greenColor: "#00e600",
yellowFrom: 1000,
yellowTo: 1020,
yellowColor: "#ff751a",
redFrom: 1020,
redTo: 1065,
redColor: "#FF0000"};
loadData();
// load new data every 15 seconds
setInterval('loadData()', 15000);
}
</script>
first, recommend using loader.js vs. the older library jsapi
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader.js from now on.
this will only change the load statement, see following snippet...
next, start by loading the data, before building anything else
once the json data is received, use it to determine which charts to draw,
according the properties specified by field1, field2, etc...
see following working snippet...
// load the google gauge visualization
google.charts.load('current', {
callback: loadData,
packages:['gauge']
});
function loadData() {
// set your channel id here
var channel_id = 248987;
// set your channel's read api key here if necessary
var api_key = '16UK5LLONGR9LCR2';
// variable for the data point
var p;
// name of the gauge
var gauge_name;
// get the data from thingspeak
$.getJSON('https://api.thingspeak.com/channels/' + channel_id + '/feed/last.json?api_key=' + api_key, function(jsonData) {
for (var key in jsonData) {
if (jsonData.hasOwnProperty(key)) {
if (key.indexOf('field') > -1) {
p = jsonData[key];
switch (key) {
case 'field1':
gauge_name = 'Tlak';
break;
case 'field2':
gauge_name = 'Vlhkost';
break;
default:
gauge_name = key;
}
displayData(key, p, gauge_name);
}
}
}
});
setInterval(loadData, 15000);
}
// display the data
function displayData(div, point, name) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
data.addRows(1);
data.setValue(0, 0, name);
data.setValue(0, 1, point);
var chartContainer = document.getElementById('gauge_div_' + div) || null;
if (chartContainer === null) {
chartContainer = document.getElementById('inner').appendChild(document.createElement('div'));
chartContainer.id = 'gauge_div_' + div;
chartContainer.className = 'gauge';
}
var chart = new google.visualization.Gauge(chartContainer);
var options = {
width: 160, height: 160, min: 955, max: 1065,
majorTicks: [950, 980, 1010, 1040, 1060], minorTicks: 10,
greenFrom: 955,
greenTo: 1000,
greenColor: "#00e600",
yellowFrom: 1000,
yellowTo: 1020,
yellowColor: "#ff751a",
redFrom: 1020,
redTo: 1065,
redColor: "#FF0000"
};
chart.draw(data, options);
}
body { background-color: #FFFFFF; }
#container { height: 100%; width: 100%; }
#inner { }
.gauge { margin: 0 auto; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="container">
<div id="inner"></div>
</div>
note: the chart container divs are added dynamically...

Google Charts: Data in the axis

This code creates a scatterplot with an image of a pie chart on it.
I'm having a problem making the data row entry to be shown in the axis of the Scatterplot.
Any idea in how to make that happen?
Many thanks :)
google.charts.load('current', {'packages':['corechart']});
function draw0hedgeChart() { var data = new google.visualization.DataTable(); data.addColumn('number', 'X'); data.addColumn('number', 'Y');
data.addRows([ [ 9.87, 6.53], ]);
var options = {
colors: ['#000000'],
legend: 'none',
title: 'Risk vs. Return with 0% Hedge Fund',
hAxis: {title: 'Risk', minValue: 3, maxValue: 11, gridlineColor: '#fff', direction: -1},
vAxis: {title: 'Return', minValue: 4, maxValue: 10, gridlineColor: '#fff'},
width:900,
height:500
};
var container = document.getElementById('chart0_div');
var chart = new google.visualization.ScatterChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var layout = chart.getChartLayoutInterface();
for (var i = 0; i < data.getNumberOfRows(); i++) {
var xPos = layout.getXLocation(data.getValue(i, 0));
var yPos = layout.getYLocation(data.getValue(i, 1));
var widget0 = container.appendChild(document.createElement('img'));
widget0.src = 'img/0.png';
widget0.className = 'chart0';
// (overlay the dot)
widget0.style.top = (yPos - 50) + 'px';
widget0.style.left = (xPos - 50) + 'px';
} });
chart.draw(data, options); }
i think you may be referring to the configuration options for...
{hAxis,vAxis,hAxes.*,vAxes.*}.ticks
hAxis.ticks - Replaces the automatically generated X-axis ticks with the specified array. Each element of the array should be either a valid tick value (such as a number, date, datetime, or timeofday)
e.g.
google.charts.load('current', {
callback: draw0hedgeChart,
packages: ['corechart']
});
function draw0hedgeChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Y');
data.addRows([
[9.87, 6.53],
]);
var ticksX = [];
var ticksY = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
ticksX.push(data.getValue(i, 0));
ticksY.push(data.getValue(i, 1));
}
var options = {
colors: ['#000000'],
legend: 'none',
title: 'Risk vs. Return with 0% Hedge Fund',
hAxis: {
title: 'Risk',
minValue: 3,
maxValue: 11,
//gridlineColor: '#fff',
direction: -1,
ticks: ticksX
},
vAxis: {
title: 'Return',
minValue: 4,
maxValue: 10,
//gridlineColor: '#fff',
ticks: ticksY
},
width:900,
height:500
};
var container = document.getElementById('chart0_div');
var chart = new google.visualization.ScatterChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var layout = chart.getChartLayoutInterface();
for (var i = 0; i < data.getNumberOfRows(); i++) {
var xPos = layout.getXLocation(data.getValue(i, 0));
var yPos = layout.getYLocation(data.getValue(i, 1));
var widget0 = container.appendChild(document.createElement('img'));
widget0.src = 'http://findicons.com/files/icons/512/star_wars/16/clone_old.png';
widget0.className = 'chart0';
// (overlay the dot)
widget0.style.position = 'absolute';
widget0.style.top = yPos + 'px';
widget0.style.left = xPos + 'px';
}
});
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart0_div"></div>

How do I add a legend and a label to my Google Pie Chart?

How can I set a legend and labels for my Google pie chart?
The deprecated method had this ability: https://developers.google.com/chart/image/docs/gallery/pie_charts
Also, how can I make it so that onclick the selected slice gets exploded from the pie a little?
Here's what I have so far:
<div id="pie_chart_div" style="width: 940px; height: 500px;"></div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(render_applicant_sources);
function render_applicant_sources() {
var data = new google.visualization.arrayToDataTable([["Source","Number of Applicants"],["Hospitality Online",222],["Indeed",22]]);
data.addColumn('string', 'Geocoder');
data.addColumn('number', 'Geocodes');
var chart = new google.visualization.PieChart(document.getElementById('pie_chart_div'));
var options = {
title: 'Scottsdale Resort & Conference Center from December 1, 2012 to December 1, 2013',
is3D: true,
colors: [ '#2483b3', '#AAC789', '#1E4147', '#437356', '#F34A53', '#FAE3B4' ],
titleTextStyle: { bold: false },
legend: { position: 'labeled' }
};
chart.draw(data, options);
google.visualization.events.addListener(chart, 'click', function(e){
var data = chart.getSelection();
if(data.length > 0) {
chart.setSelection([]);
}
});
}
</script>
http://jsfiddle.net/xHwZW/
You need to use a "select" event handler, and set the chart's slices.<slice index>.offset option:
google.visualization.events.addListener(chart, 'select', function() {
var selection = chart.getSelection();
if (selection.length > 0) {
if (!options.slices || !options.slices[selection[0].row]) {
// if this is the first time the user clicked on the pie,
// or if the user clicks on an unexploded slice,
// unexplode all slices and explode the selected slice
options.slices = [];
options.slices[selection[0].row] = {
offset: 0.4
};
}
else {
// otherwise the user clicked on an exploded slice, so unexplode all slices
options.slices = [];
}
chart.draw(data, options);
}
else {
options.slices = [];
chart.draw(data, options);
}
});
See working example: http://jsfiddle.net/asgallant/R8yAK/

Categories