Easiest Way to AutoRefresh Google Charts embeded within a page - javascript

I have two files, one outputting data from a MySQL database and one drawing a Google Graph within a page with other metrics:
grab_twitter_stats.php Output:
[15, 32], [14, 55], [13, 45], [12, 52], [11, 57], [10, 55], [9, 58], [8, 42], [7, 44], [6, 40], [5, 54], [4, 52], [3, 60], [2, 71], [1, 43],
index.php Output:
<div id="curve_chart" style="width: 900px; height: 500px">
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Minutes', 'Tweets'],
<?php require('grab_twitter_stats.php');?>
]);
var options = {
title: 'Tweets in last 15 Minutes',
curveType: 'function',
hAxis: {
title: 'Last 15 Minutes',
direction: '-1'
},
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</div>
This draws a graph that shows tweets in the last 15 minutes. I can get the graph to appear once, but upon trying to load a SetInterval, it does not refresh the Google Graph on the interval. I have tried wrapping the entire drawChart() function in it, and it doesn't seem to be working. I tried using AJAX but it is not formatted in JSON so ajax doesn't like it. Any suggestions on the easiest way to make this graph auto refresh?

although not JSON, you can still use ajax, even with plain text
something like this should get you close...
google.charts.load('current', {
callback: function () {
drawChart();
setInterval(drawChart, (15 * 60 * 1000));
function drawChart() {
$.ajax({
url: 'grab_twitter_stats.php',
type: 'get',
success: function (txt) {
// check for trailing comma
if (txt.slice(-1) === ',') {
txt = txt.substring(0, txt.length - 1);
}
var txtData = JSON.parse('[["Minutes", "Tweets"],' + txt + ']');
var data = google.visualization.arrayToDataTable(txtData);
var options = {
title: 'Tweets in last 15 Minutes',
curveType: 'function',
hAxis: {
title: 'Last 15 Minutes',
direction: '-1'
},
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
});
}
},
packages: ['corechart']
});

Related

What should I adjust in google charts code to get rid of some properties? (javascript)

What should I change in google charts code example to get rid of all slice % and leave only % for one slice, and also the column that shows what each colour represents?
Link to google chart - https://developers.google.com/chart/interactive/docs/gallery/piechart#donut
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="donutchart" style="width: 900px; height: 500px;"></div>
</body>
</html>
I only want the values circled in the image below:
Try changing options to:
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
slices: {
2: { textStyle : {color:'transparent'} },
3: { textStyle : {color:'transparent'} },
4: { textStyle : {color:'transparent'} },
5: { textStyle : {color:'transparent'} },
}
};
This will set slices 2,3,4,5 to a transparent text colour.
Adapted from: https://stackoverflow.com/a/27010671/608312
#JakeSteam this is the code I have so far.. I could 'make transparent' lebel for 'others' but in this case I would like to get rid of '%' so only slice keeps the value and the colour.
<html>
<head>
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Metric', 'Score', 'Site'],
['Uniqueness', 6.178, 'https://www.google.com/'],
['', 93.82, 'https://www.bing.com/']
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
legend: 'none',
title: 'Unique Identifiability',
pieHole: 0.6,
colors: ['#EE7023', '#808080']
};
var chart = new google.visualization.PieChart(document.getElementById('uniqueness'));
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
if (selection.length > 0) {
window.open(data.getValue(selection[0].row, 2), '_blank');
console.log(data.getValue(selection[0].row, 2));
}
});

How to draw a google column chart in angular 6 project?

I'm using angular 6 and I want to draw a column chart of Google. I found below codes from documantation but I don't know how to use it in my app?
html
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="top_x_div" style="width: 800px; height: 600px;"></div>
js
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['Move', 'Percentage'],
["King's pawn (e4)", 44],
["Queen's pawn (d4)", 31],
["Knight to King 3 (Nf3)", 12],
["Queen's bishop pawn (c4)", 10],
['Other', 3]
]);
var options = {
width: 800,
legend: { position: 'none' },
chart: {
title: 'Chess opening moves',
subtitle: 'popularity by percentage' },
axes: {
x: {
0: { side: 'top', label: 'White to move'} // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
// Convert the Classic options to Material options.
chart.draw(data, google.charts.Bar.convertOptions(options));
};
You need to first declare in your component like this:
declare var google:any;
then your component will know what your are refering to when you call
google.charts.load..
Everything else looks good..

How to sync and display the tooltips of different google charts?

I'm creating different google charts on two iframes for comparison purpose. To achieve that I need to sync the mouse click on both the charts and display the tooltips at the particular position of the click.
Although I've achieved syncing the mouse click by using the chart_2.setSelection(chart_1.getSelection()); method.
But the tooltip doesn't get displayed on the second chart at that specific position:
The only way to display the tooltip on the second chart is by clicking the chart and then the tooltip gets activated:
After it gets activated then the tooltip syncs with the first chart and works flawlessly with each click:
What I'm trying to achieve is to display the tooltip on the second chart without manually activating it but it rather gets displayed with each click on the first chart.
set the following option to cause the tooltip to be displayed on --> setSelection
var options = {
tooltip: {
trigger: 'both'
}
};
see following working snippet,
when the 'ready' event fires, a selection is made,
to demonstrate the tooltip is displayed
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['x', 'y0', 'y1', 'y2', 'y3'],
[1, 10, 15, 20, 25],
[2, 12, 18, 24, 30],
[3, 14, 21, 28, 35],
[4, 16, 24, 32, 40]
]);
var options = {
pointSize: 4,
tooltip: {
trigger: 'both'
},
width: 360
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
chart.setSelection([{row: 2, column: 1}]);
});
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

How to rename y axes in Google Charts API?

I am trying to rename the labels on the axes to levels like low|medium| high instead of percentages in my bar chart. Could anyone suggest me a way of accomplishing it?
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Programming Languages', 'Expertise Level %'],
['Java', 100],
['C', 80],
['Python', 100],
['Web UX', 100],
['Matlab', 70]
]);
var options = {
bars: 'vertical' // Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
unfortunately, no option available for Material charts...
many options are not supported, see --> Tracking Issue for Material Chart Feature Parity
however, using a Classic chart, the vAxis.ticks option can be used to customize the axis labels...
use the formatted value of each tick to display --> Low, Medium, High
vAxis: {
ticks: [
{v: 33.33, f: 'Low'},
{v: 66.67, f: 'Medium'},
{v: 100, f: 'High'}
]
}
see following working snippet,
which also uses option --> theme: 'material'
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Programming Languages', 'Expertise Level %'],
['Java', 100],
['C', 80],
['Python', 100],
['Web UX', 100],
['Matlab', 70]
]);
var options = {
theme: 'material',
vAxis: {
ticks: [
{v: 33.33, f: 'Low'},
{v: 66.67, f: 'Medium'},
{v: 100, f: 'High'}
]
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('barchart'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="barchart"></div>
note:
Material --> google.charts.Bar
Classic --> google.visualization.ColumnChart

Using different symbols for plotting data not working

I am attempting to use a different symbol for one of my data series on my flot graph as it is at a much larger scale then the rest of the data. I am using this example as reference: http://www.flotcharts.org/flot/examples/symbols/index.html
Here is what I have so far:
My includes:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.flot.js"></script>
<script type="text/javascript" src="jquery.flot.symbol.js"></script>
I then configure my flot options like so:
var options = {
grid: {hoverable : true},
xaxis: { mode: "time", timeformat: "%H:%M", tickLength: 1},
series: { points : { show: true } }
};
I then actually plot the data:
$.plot('#placeholder', [{
data: my_data,
lines: { show : true},
points: { symbol: "square"},
color: '#CB4B4B',
label: 'My Data'
}], options);
}
However, flot is still graphing the points as the default circle. I get no error messages in firebug and I have even tried adding a logging message in the jquery.flot.symbol.js library itself to see if the "square" handler is even being called like so:
var handlers = {
square: function (ctx, x, y, radius, shadow) {
console.log("Square handler was called");
// pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2
var size = radius * Math.sqrt(Math.PI) / 2;
ctx.rect(x - size, y - size, size + size, size + size);
},
I am getting no console messages so I am assuming the handler is not getting called correctly. Am I missing something here?
EDIT:
Example of data I am trying to plot:
var d1 = [
[1364342400000, 208],
[1364346000000, 107],
[1364353200000, 42],
[1364371200000, 1680],
[1364360400000, 52],
[1364349600000, 67],
[1364385600000, 1118],
[1364367600000, 163],
[1364382000000, 1359],
[1364378400000, 1468],
[1364389200000, 1023],
[1364356800000, 63],
[1364374800000, 1601],
[1364392800000, 556],
[1364364000000, 84],
],
d2 = [
[1364342400000, 86],
[1364346000000, 42],
[1364353200000, 13],
[1364371200000, 458],
[1364360400000, 10],
[1364349600000, 22],
[1364385600000, 453],
[1364367600000, 45],
[1364382000000, 369],
[1364378400000, 379],
[1364389200000, 358],
[1364356800000, 17],
[1364374800000, 471],
[1364392800000, 147],
[1364364000000, 16],
],
d3 = [
[1364342400000, 7],
[1364346000000, 5],
[1364382000000, 11709],
[1364371200000, 58336],
[1364360400000, 1],
[1364349600000, 1],
[1364367600000, 2],
[1364389200000, 1191],
[1364378400000, 9085],
[1364385600000, 4688],
[1364374800000, 9386],
[1364392800000, 1140],
[1364364000000, 1],
];
I have also edited my options parameter and how the plot function is called:
var options = {
grid: {hoverable : true},
xaxis: { mode: "time", timeformat: "%H:%M", tickLength: 1}
};
$.plot("#placeholder", [{
data: d1,
lines: { show : true },
points: { show: true},
color: '#EDC240',
label: "d1"
}, {
data: d2,
lines: { show : true },
points: { show : true},
color: '#AFD8F8',
label: "d2"
}, {
data: d3,
yaxis: 2,
lines: { show : true},
points: { show: true, symbol: "square"},
color: '#CB4B4B',
label: "d3"
}], options);
I am also sure that the symbol library is being included because I have added some logging itself to the library and that is showing up fine.
I see no issue with what you've done. I made a quick working example here: http://jsfiddle.net/ryleyb/shLtU/1/
I would guess that you haven't included the symbol library (even though you say you have).
Or show your data, might somehow be an issue there (doubtful?).
This is the full flot code I ran to make a working example (plus including flot and the symbol library):
$.plot('#placeholder', [{
data: [
[1, 1],
[2, 3],
[4, 4],
[5, 9]
],
lines: {
show: true
},
points: {
show: true,
symbol: "square"
},
color: '#CB4B4B',
label: 'My Data'
}]);

Categories

Resources