help, I want to create stacked chart from JSON in google chart, honestly my problem is var data = google.visualization.arrayToDataTable([ this is my codes
<?php
$tmp = array();
require "configdashboard.php";
/*
select the 3 columns of interest, assinging aliases for laziness purposes
*/
$sql = "SELECT devices.device_id AS device_id, devices.hostname AS hostname, devices.ip, devices.uptime, SUM(storage.storage_used) AS storage_used, SUM(storage.storage_free) AS storage_free , storage.storage_descr AS storage_descr
FROM storage
INNER JOIN devices ON storage.device_id = devices.device_id GROUP BY devices.device_id, storage.storage_descr";
$conn = mysqli_connect('localhost', 'root', '', 'monitoring');
$query = mysqli_query($conn, $sql);
$fetch = mysqli_fetch_assoc($query);
if ($stmt = $connection->query($sql)) {
while ($row = $stmt->fetch_assoc()) {
/* Add each row with named columns - which makes working with the JSON in Javascript easier IMO */
$tmp[] = array(
'device_id' => $row['device_id'],
'storage_used' => $row['storage_used'],
'storage_free' => $row['storage_free'],
'hostname' => $row['hostname'],
'storage_descr' => $row['storage_descr']
);
}
}
# create the JSON string
$json = json_encode($tmp);
//$json=json_encode( $fetch );
//print_r ($json);
?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
var my_2d = <?php echo $json; ?>;
google.charts.load('current', {
packages: ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
if (Object.keys(my_2d).length > 0) {
for (i = 0; i < my_2d.length; i++) {
var data = google.visualization.arrayToDataTable([
['Task', 'Server Devices ' + my_2d[i].device_id + ' ' + my_2d[i].hostname],
['Used', parseInt(my_2d[i].storage_used)],
['Free', parseInt(my_2d[i].storage_free)]
]);
var options_fullStacked = {
isStacked: 'percent',
height: 300,
legend: {
position: 'top',
maxLines: 2
},
hAxis: {
minValue: 0,
ticks: [0, .3, .6, .9, 1]
}
};
var table = document.getElementById("table_chart");
if (i % 2 == 0) {
var tr = document.createElement("tr");
tr.setAttribute("class", "row_chart")
table.appendChild(tr)
}
var row_charts = document.getElementsByClassName("row_chart")
var td = document.createElement("td");
var div = document.createElement("div")
div.setAttribute("id", 'chart_div_' + i)
div.setAttribute("style", 'width: auto; height: auto; display: block; margin: auto;')
var lastTr = row_charts.length - 1
row_charts[lastTr].appendChild(td)
td.appendChild(div)
var chart = new google.visualization.BarChart(div);
chart.draw(data, options_fullStacked);
}
}
}
</script>
this is my database
and i want to create like this *note /, /run etc is storage_descr
but my output now
Looks like you have two separate series, Used and Free. You want one series as a stacked bar.
Try follwing the was they sample the table and chart setup here:
https://developers.google.com/chart/interactive/docs/gallery/barchart
var options = {
width: 600,
height: 400,
legend: { position: 'top', maxLines: 3 },
bar: { groupWidth: '75%' },
isStacked: true
};
Related
I would like to fix y-axis position when scrolling horizontally.
Here's an example that works but without using Angular
$(document).ready(function () {
function generateLabels() {
var chartLabels = [];
for (x = 0; x < 100; x++) {
chartLabels.push("Label" + x);
}
return chartLabels;
}
function generateData() {
var chartData = [];
for (x = 0; x < 100; x++) {
chartData.push(Math.floor((Math.random() * 100) + 1));
}
return chartData;
}
function addData(numData, chart) {
for (var i = 0; i < numData; i++) {
chart.data.datasets[0].data.push(Math.random() * 100);
chart.data.labels.push("Label" + i);
var newwidth = $('.chartAreaWrapper2').width() + 60;
$('.chartAreaWrapper2').width(newwidth);
}
}
var chartData = {
labels: generateLabels(),
datasets: [{
label: "Test Data Set",
data: generateData()
}]
};
$(function () {
var rectangleSet = false;
var canvasTest = $('#chart-Test');
var chartTest = new Chart(canvasTest, {
type: 'bar',
data: chartData,
maintainAspectRatio: false,
responsive: true,
options: {
tooltips: {
titleFontSize: 0,
titleMarginBottom: 0,
bodyFontSize: 12
},
legend: {
display: false
},
scales: {
xAxes: [{
ticks: {
fontSize: 12,
display: false
}
}],
yAxes: [{
ticks: {
fontSize: 12,
beginAtZero: true
}
}]
},
animation: {
onComplete: function () {
if (!rectangleSet) {
var sourceCanvas = chartTest.chart.canvas;
var copyWidth = chartTest.scales['y-axis-0'].width;
var copyHeight = chartTest.scales['y-axis-0'].height + chartTest.scales['y-axis-0'].top + 10;
var targetCtx = document.getElementById("axis-Test").getContext("2d");
targetCtx.canvas.width = copyWidth;
targetCtx.drawImage(sourceCanvas, 0, 0, copyWidth, copyHeight, 0, 0, copyWidth, copyHeight);
var sourceCtx = sourceCanvas.getContext('2d');
sourceCtx.clearRect(0, 0, copyWidth, copyHeight);
rectangleSet = true;
}
},
onProgress: function () {
if (rectangleSet === true) {
var copyWidth = chartTest.scales['y-axis-0'].width;
var copyHeight = chartTest.scales['y-axis-0'].height + chartTest.scales['y-axis-0'].top + 10;
var sourceCtx = chartTest.chart.canvas.getContext('2d');
sourceCtx.clearRect(0, 0, copyWidth, copyHeight);
}
}
}
}
});
addData(5, chartTest);
});
});
.chartWrapper {
position: relative;
}
.chartWrapper > canvas {
position: absolute;
left: 0;
top: 0;
pointer-events: none;
}
.chartAreaWrapper {
width: 600px;
overflow-x: scroll;
}
<script src="https://github.com/chartjs/Chart.js/releases/download/v2.6.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chartWrapper">
<div class="chartAreaWrapper">
<div class="chartAreaWrapper2">
<canvas id="chart-Test" height="300" width="1200"></canvas>
</div>
</div>
<canvas id="axis-Test" height="300" width="0"></canvas>
</div>
When I use this in my angular example , it does not work anymore, the axis does not follow the scroll
Here's a stackblitz reproduction
In your StackBlitz, the section (rectanlge) of the y-axis is correctly created on the target canvas and removed from the source canvas. The problem is that the wrong div is horizontally scrolled. This can be fixed by changing the template and corresponding css.
Please have a look at the following StackBlitz.
UPDATE (dynamic data)
In cases where the chart component receives dynamically changing data through an #Input() property, your component needs to implement the OnChange lifecycle hook.
See the following StackBlitz.
Please note that this code is far from being optimized. Instead of creating the chart from scratch on every data change, you should simply update the data and options on the existing chart.
So I have database where that gets random values at random times. example:
2019-02-22 12:05, 500
2019-02-22 12:15, 2
2019-02-22 12:19, 90
So I want to show it in a line chart. this is my code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"><script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart', 'line']});
google.setOnLoadCallback(drawAxisTickColors);
function drawAxisTickColors() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Price');
data.addColumn('datetime', 'Date');
var dateArr2 = (<?php echo json_encode($dateArr); ?>);
var number = (<?php echo json_encode($number); ?>);
var length = Math.min(dateArr2.length, number.length);
var rows = [];
for (var i = 0; i < length; ++i) {
rows.push([number[i], new Date(dateArr2[i]) ]);
}
data.addRows(rows);
var options = {
// backgroundColor: '#E4E4E4',
curveType: 'function',
chartArea: {
left: 0,
top: 0,
right: 0,
bottom: 0,
width: "100%",
height: "100%"
},
hAxis: {
textPosition: 'none',
baselineColor: 'none',
gridlines: {
color: 'none'
},
},
vAxis: {
textPosition: 'none',
baselineColor: 'none',
gridlines: {
color: 'none'
}
},
colors: ['#2098d4', '#ffffff'],
legend: 'none'
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
chart.draw(data, options);
}
</script>
and this is how my database looks like this:
But my chart looks like this:
What am I doing wrong, please help.
EDIT
tried this:
number = number.map(Number);
after
var number = (<?php echo json_encode($number); ?>);
this is the result:
each chart has a specific data format,
for LineChart, the first column is used as the x-axis,
each additional column appears on the y-axis.
in this case, to have the date on the x-axis,
just swap the order of the columns...
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Price');
and...
rows.push([new Date(dateArr2[i]), number[i]]);
ALSO, you're using an old version of google charts.
jsapi should no longer be used, see update library loader code,
this will only change the load statement.
from...
google.load('visualization', '1', {packages: ['corechart', 'line']});
google.setOnLoadCallback(drawAxisTickColors);
to...
google.charts.load('current', {packages:['corechart']});
google.charts.setOnLoadCallback(drawAxisTickColors);
note: the line package is not needed, it is for material charts...
google.charts.Line
you're using a classic chart...
google.visualization.LineChart
I am trying to add a Play/Pause button to the Advanced API controls, I have the button.value changing from the ascii #9654 to #9646 but the rest of the code to start the animation and stop it is not working? The sphere will rotate if the 'requestanimationframe' is contained within the 'init()' of the WebGl it's self. You can see the working sphere at No controls and the one I'm adding controls in Placing controls but animation play/pause not working, thanks for any ideas.
I left in //hard coded markers if you need to run it yourself just comment out the php section of DB access.
<!DOCTYPE HTML>
<html>
<head>
<script src="http://www.webglearth.com/v2/api.js"></script>
<script>
function initialize() {
var options = {
sky: true,
atmosphere: true,
dragging: true,
tilting: false
};//options
var earth = new WE.map('earth_div');
earth.setView([30.0, -87.65], 3);
WE.tileLayer('http://data.webglearth.com/natural-earth-color/{z}/{x}/{y}.jpg', {
tileSize: 256,
bounds: [[-85, -180], [85, 180]],
minZoom: 2,
maxZoom: 9,
tms: true
}).addTo(earth);//tilelayer
var toner = WE.tileLayer('http://tile.stamen.com/toner/{z}/{x}/{y}.png', {
opacity: 0.25
});//toner
toner.addTo(earth);
earth.setZoom(3);
document.getElementById('zoom_level').addEventListener('change', function(e) {
earth.setZoom(e.target.value);
});//setZoom
// earth.setTilt(40);
// document.getElementById('tilt_level').addEventListener('change', function(e) {
// earth.setTilt(e.target.value);
// });//setTilt-not working look at .setview
/* // Add markers - Hard coded works.
var marker = WE.marker([48.45, 34.9833], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker.bindPopup("86.110.118.194", {maxWidth: 90, closeButton: true}).openPopup();
var marker2 = WE.marker([41.85, -87.65], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker2.bindPopup("174.221.5.127", {maxWidth: 90, closeButton: true}).openPopup();
var marker3 = WE.marker([44.3051,-69.977], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker3.bindPopup("142.105.199.149", {maxWidth: 90, closeButton: true}).openPopup();
*/
//Get GPS lat/lon from sql Db for markers
<?php
include('ts.php');
// Add markers
$ct = 0;
$i = 1;
$lat1 = ""; $lat2 = "";
$lon1 = ""; $lon2 = "";
$row = array();
$rows = array($row);
$con = mysql_connect("localhost","User","Password");
$db_selected = mysql_select_db("DB", $con);
if (!$db_selected){echo mysql_errno($con) . ": " . mysql_error($con) . "\n";}
$query = "SELECT `gpslat`, `gpslon`, `ip` FROM `visitor_tracker` ORDER BY `gpslat` DESC";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$lat1 = $row[0];
//$lon1 = $row[1];
if ($ct == 0) {$rows[] = $row;
$lat2 = $rows[$i][0];
//$lon2 = $rows[$i][1];
}//if
Else {if ($lat1 != $lat2){
$rows[] = $row;
$i = $i+1;
$lat2 = $rows[$i][0];
//$lon2 = $rows[$i-1][1];
}//if
}//else
$ct = $ct+1;
}//while
mysql_free_result($result);
mysql_close($con);
?>
// Populate markers
var markers = <?php echo json_encode($rows); ?>;
var ygpslat = <?php echo json_encode($gpslat); ?>;
var ygpslon = <?php echo json_encode($gpslon); ?>;
var yip = <?php echo json_encode($ip); ?>;
for(var i = 1, len = markers.length; i < len; i++) {
var marker = WE.marker([markers[i][0],markers[i][1]], 'http://eagleeye360.com/worldmap/pin_green.jpg', 4, 4).addTo(earth);
marker.bindPopup(markers[i][2], {maxWidth: 100, closeButton: true}).closePopup();
}//for
//Your marker
var marker = WE.marker([ygpslat,ygpslon], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker.bindPopup("<center>You</br>"+yip, {maxWidth: 100, closeButton: true}).openPopup();
}//init()
function rotate_play_pause() {
var status = document.getElementById("rotate_button");
if (status.value == String.fromCharCode(9654)) {
document.getElementById("rotate_button").value = String.fromCharCode(9646);
// Start a simple rotation animation
var before = null;
requestAnimationFrame(function animate(now) {
var c = earth.getPosition();
var elapsed = before? now - before: 0;
before = now;
earth.setCenter([c[0], c[1] - 0.1*(elapsed/30)]);
requestAnimationFrame(animate);
});//requestAnimationFrame
} else {
document.getElementById("rotate_button").value = String.fromCharCode(9654);
cancelAnimationFrame(animate);
}//if else
}//function rotate_play_pause()
// document.getElementById('cesium-credit-text').innerHTML = "EagleEye360.com-Visitors/Bots/HackAttempts";
</script>
<style type="text/css">
html, body{padding: 0; margin: 0; background-color: black;}
#earth_div{top: 0; right: 0; bottom: 0; left: 0; position: absolute !important;}
#coords{position: absolute; bottom: 10px; right: 10px; z-index: 100000;}
#buttons {position: absolute; bottom:10px; left: 10px; color: #808080;}
</style>
<title>EagleEye360 Test 1</title>
</head>
<body onload="initialize()">
<div id="earth_div"></div>
<div id="buttons">
<center><input type="button" id="rotate_button" value="▶" class="play" onclick="rotate_play_pause();"><center/><br>
<center>Zoom</center>
2<input type="range" id="zoom_level" min="2" max="9" step="1.0" value="3.0">9<br>
<center>Tilt</center>
40°<input type="range" id="tilt_level" min="40" max="130" step="5" value="40">130°<br>
</div>
</body>
</html>
After 10 days of trying, I have solved the issue with this code :)
The problem was that Java Script does not pass vars as other languages it passes a dynamic of the var so anything done to a var with in a function will leave the original var unchanged - unless it is a Global var.
I added Global vars: Earth and myReq(for canx the request) the entire code is:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="CSS/vertical-text.css" type="text/css"/>
<script src="http://www.webglearth.com/v2/api.js"></script>
<script>
var earth = undefined;
var myReq;
function initialize() {
var options = {
sky: true,
atmosphere: true,
dragging: true,
tilting: false,
scrollWheelZoom: false
};//options
earth = new WE.map('earth_div');
earth.setView([30.0, -87.65], 3);
WE.tileLayer('http://data.webglearth.com/natural-earth-color/{z}/{x}/{y}.jpg', {
tileSize: 256,
bounds: [[-85, -180], [85, 180]],
minZoom: 2,
maxZoom: 9,
tms: true,
attribution: '© EagleEye360.com'
}).addTo(earth);//tilelayer
var toner = WE.tileLayer('http://tile.stamen.com/toner/{z}/{x}/{y}.png', {
opacity: 0.15 // or use http://{s}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png
});//toner
toner.addTo(earth);
document.getElementById('opacity2').addEventListener('change', function(e) {
toner.setOpacity(e.target.value);
});//set opacity
earth.setZoom(3);
document.getElementById('zoom_level').addEventListener('change', function(e) {
earth.setZoom(e.target.value);
});//setZoom
//rotate_play_pause();
document.getElementById('rotate_button').addEventListener('change', function(e) {
rotate_play_pause();
});//rotate_play_pause()
// earth.setTilt(40);
// document.getElementById('tilt_level').addEventListener('change', function(e) {
// earth.setTilt(e.target.value);
// });//setTilt-not working look at .setview
/* // Add markers - Hard coded works.
var marker = WE.marker([48.45, 34.9833], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker.bindPopup("86.110.118.194", {maxWidth: 90, closeButton: true}).openPopup();
var marker2 = WE.marker([41.85, -87.65], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker2.bindPopup("174.221.5.127", {maxWidth: 90, closeButton: true}).openPopup();
var marker3 = WE.marker([44.3051,-69.977], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker3.bindPopup("142.105.199.149", {maxWidth: 90, closeButton: true}).openPopup();
*/
<?php
include('ts.php');
// Add markers
$ct = 0;
$i = 1;
$lat1 = ""; $lat2 = "";
$lon1 = ""; $lon2 = "";
$row = array();
$rows = array($row);
$con = mysql_connect("localhost","hogansba_Jon","Tigger09<>");
$db_selected = mysql_select_db("hogansba_EagleEye", $con);
if (!$db_selected){echo mysql_errno($con) . ": " . mysql_error($con) . "\n";}
$query = "SELECT `gpslat`, `gpslon`, `ip` FROM `visitor_tracker` ORDER BY `gpslat` DESC";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$lat1 = $row[0];
//$lon1 = $row[1];
if ($ct == 0) {$rows[] = $row;
$lat2 = $rows[$i][0];
//$lon2 = $rows[$i][1];
}//if
Else {if ($lat1 != $lat2){
$rows[] = $row;
$i = $i+1;
$lat2 = $rows[$i][0];
//$lon2 = $rows[$i-1][1];
}//if
}//else
$ct = $ct+1;
}//while
mysql_free_result($result);
mysql_close($con);
?>
// Populate markers
var markers = <?php echo json_encode($rows); ?>;
var ygpslat = <?php echo json_encode($gpslat); ?>;
var ygpslon = <?php echo json_encode($gpslon); ?>;
var yip = <?php echo json_encode($ip); ?>;
for(var i = 1, len = markers.length; i < len; i++) {
var marker = WE.marker([markers[i][0],markers[i][1]], 'http://eagleeye360.com/worldmap/pin_green.jpg', 4, 4).addTo(earth);
marker.bindPopup(markers[i][2], {maxWidth: 100, closeButton: true}).closePopup();
}//for
//Your marker
var marker = WE.marker([ygpslat,ygpslon], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker.bindPopup("<div class='container'><div class='rotated-text'><span class='rotated-text__inner'><center><?php echo 'You-',$ip?><center/></span></div></div>", {maxWidth: 14, closeButton: true}).openPopup();
earth.setView([ygpslat,ygpslon], 3);
}//init()
function rotate_play_pause() {
var before = null;
var status = document.getElementById("rotate_button");
if (status.value == String.fromCharCode(9654)) {
document.getElementById("rotate_button").value = String.fromCharCode(9646);
// Start a simple rotation animation
requestAnimationFrame(function animate(now) {
var c = earth.getPosition();
var elapsed = before? now - before: 0;
before = now;
earth.setCenter([c[0], c[1] - 0.1*(elapsed/30)]);
myReq = requestAnimationFrame(animate);
});//requestAnimationFrame
} else {
cancelAnimationFrame(myReq);
document.getElementById("rotate_button").value = String.fromCharCode(9654);
}//if else
}//function rotate_play_pause()
// document.getElementById('cesium-credit-text').innerHTML = "EagleEye360.com-Visitors/Bots/HackAttempts";
</script>
<style type="text/css">
html, body{padding: 0; margin: 0; background-color: black;}
#earth_div{top: 0; right: 0; bottom: 0; left: 0; position: absolute !important;}
#coords{position: absolute; bottom: 10px; right: 10px; z-index: 100000;}
#buttons {position: absolute; bottom:10px; left: 10px; color: #808080;}
</style>
<title>EagleEye360 Test 1</title>
</head>
<body onload="initialize()">
<div id="earth_div"></div>
<div id="buttons">
<center><input type="button" id="rotate_button" value="▶" class="play" onclick="rotate_play_pause();"><center/><br>
<center>Zoom</center>
2<input type="range" id="zoom_level" min="2" max="9" step="1.0" value="3.0">9<br>
<center>Streetmap opacity</center>
0<input type="range" id="opacity2" min="0" max="1" step="0.05" value="0.15">1<br>
<center><p>Total Hits: <?php echo $ct ?></br>Unique Visitors: <?php echo $i ?><p/></center>
</div>
</body>
</html>
You can see it working Here I will leave it up for about a month after that it will no longer be available.
Jon
trying to compare two sensor readings - the data is coming from thingspeak. I've got the zoom part working, but for some reason I cant get the scroll to work.
<script type="text/javascript">
// variables for the first series
var series_1_channel_id = 43330;
var series_1_field_number = 4;
var series_1_read_api_key = '7ZPHNX2SXPM0CA1K';
var series_1_results = 480;
var series_1_color = '#d62020';
var series_1_name = 'Zims Sensor';
// variables for the second series
var series_2_channel_id = 45473;
var series_2_field_number = 2;
var series_2_read_api_key = 'N12T3CWQB5IWJAU9';
var series_2_results = 480;
var series_2_color = '#00aaff';
var series_2_name = 'UVM30a';
// chart title
var chart_title = 'UV Sensors Zim / UVM30A';
// y axis title
var y_axis_title = 'UV Index';
// user's timezone offset
var my_offset = new Date().getTimezoneOffset();
// chart variable
var my_chart;
// when the document is ready
$(document).on('ready', function() {
// add a blank chart
addChart();
// add the first series
addSeries(series_1_channel_id, series_1_field_number, series_1_read_api_key, series_1_results, series_1_color, series_1_name);
// add the second series
addSeries(series_2_channel_id, series_2_field_number, series_2_read_api_key, series_2_results, series_2_color, series_2_name);
});
// add the base chart
function addChart() {
// variable for the local date in milliseconds
var localDate;
// specify the chart options
var chartOptions = {
chart: {
renderTo: 'chart-container',
defaultSeriesType: 'line',
zoomType: 'x', // added here
backgroundColor: '#ffffff',
events: { }
},
title: { text: chart_title },
plotOptions: {
series: {
marker: { radius: 3 },
animation: true,
step: false,
borderWidth: 0,
turboThreshold: 0
}
},
tooltip: {
// reformat the tooltips so that local times are displayed
formatter: function() {
var d = new Date(this.x + (my_offset*60000));
var n = (this.point.name === undefined) ? '' : '<br>' + this.point.name;
return this.series.name + ':<b>' + this.y + '</b>' + n + '<br>' + d.toDateString() + '<br>' + d.toTimeString().replace(/\(.*\)/, "");
}
},
xAxis: {
type: 'datetime',
scrollbar: {
enabled: true,
barBackgroundColor: 'gray',
barBorderRadius: 7,
barBorderWidth: 0,
buttonBackgroundColor: 'gray',
buttonBorderWidth: 0,
buttonArrowColor: 'yellow',
buttonBorderRadius: 7,
rifleColor: 'yellow',
trackBackgroundColor: 'white',
trackBorderWidth: 1,
trackBorderColor: 'silver',
trackBorderRadius: 7
},
title: { text: 'Date' }
},
yAxis: { title: { text: y_axis_title } },
exporting: { enabled: true },
legend: { enabled: true },
credits: {
text: 'ThingSpeak.com',
href: 'https://thingspeak.com/',
style: { color: '#D62020' }
}
};
// draw the chart
my_chart = new Highcharts.Chart(chartOptions);
}
// add a series to the chart
function addSeries(channel_id, field_number, api_key, results, color, name) {
var field_name = 'field' + field_number;
// get the data with a webservice call
$.getJSON('https://api.thingspeak.com/channels/' + channel_id + '/fields/' + field_number + '.json?offset=0&round=2&results=' + results + '&api_key=' + api_key, function(data) {
// blank array for holding chart data
var chart_data = [];
// iterate through each feed
$.each(data.feeds, function() {
var point = new Highcharts.Point();
// set the proper values
var value = this[field_name];
point.x = getChartDate(this.created_at);
point.y = parseFloat(value);
// add location if possible
if (this.location) { point.name = this.location; }
// if a numerical value exists add it
if (!isNaN(parseInt(value))) { chart_data.push(point); }
});
// add the chart data
my_chart.addSeries({ data: chart_data, name: data.channel[field_name], color: color });
});
}
// converts date format from JSON
function getChartDate(d) {
// offset in minutes is converted to milliseconds and subtracted so that chart's x-axis is correct
return Date.parse(d) - (my_offset * 60000);
}
</script>
<style type="text/css">
body { background-color: white; height: 100%; margin: 0; padding: 0; }
#chart-container { width: 800px; height: 400px; display: block; position:absolute; bottom:0; top:0; left:0; right:0; margin: 5px 15px 15px 0; overflow: hidden; }
</style>
<!DOCTYPE html>
<html style="height: 100%;">
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.highcharts.com/stock/highstock.js"></script>
<script type="text/javascript" src="//thingspeak.com/exporting.js"></script>
</head>
<body>
<div id="chart-container">
// <img alt="Ajax loader" src="//thingspeak.com/assets/ajax-loader.gif" style="position: absolute; margin: auto; top: 0; left: 0; right: 0; bottom: 0;" />
</div>
</body>
</html>
I would also like to get the chart updating automatically, so any help on that score would also be appreciated. The final issue I am having is trying to get the legend to display the sensor names properly: UV Index (red) should read "Zims Sensor" and UV Index (blue) should read "UVM30A"
Unfortunately I am not a developer, so I am trying to figure out how it works. I have some knowledge about PHP, HTML and CSS but unfortunately none about JavaScript. Below is my current code of Google Charts Data, it's imported by a module and the javascript code is in places inside the PHP file. Here is my code:
$js = "
google.setOnLoadCallback({$funcChart});
function {$funcChart}() {
var data = google.visualization.arrayToDataTable(".json_encode($data).");
var options = ".json_encode($options).";
var chart = new google.visualization.{$chart}(document.getElementById('{$container}'));
chart.draw(data, options);
}";
if(strpos($width, '%') !== false) {
JHtml::_('JABehavior.jquery');
$js .= "
jQuery(document).ready(function () {
jQuery(window).resize(function(){
{$funcChart}();
});
});
";
}
$doc = JFactory::getDocument();
$doc->addScriptDeclaration($js);
require JModuleHelper::getLayoutPath($module->module, $params->get('layout', 'default'));
}
How do I add a responsive function into the above code? The current chart looks weird on my page; http://goo.gl/v1GVWk
If you open the page and scroll to the "Trekking Map" tab then you will see the chart, but it looks very bad.
Try Using Following Code
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(initChartExpertBottom);
$(window).on("resize", function (event) {
initChartExpertBottom();
});
function initChartExpertBottom() {
var options = {
legend:'none',
width: '100%',
height: '100%',
tooltip: { isHtml: true },
chartArea: {left: "3%",top: "3%",height: "94%",width: "94%"},
colors: ['#7CB5EC', '#5C5C61','#16c104'],
pieHole: 0.50,
pieStartAngle: -90,
is3D: false,
pieSliceText: 'none',
};
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
["Hide" , (11+2)] //addition of value of all elements
]);
drawChartExpertBottom(data, options);
}
function drawChartExpertBottom(data, options) {
var tooltip = [
Math.round((11/(11+2))*100) + "%",
Math.round((2/(11+2))*100)+ "%",
"Hiii3",
];
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
var sliceid = 0;
function eventHandler(e){
chart.setSelection([e]);
try {
selection = chart.getSelection();
sliceid = selection[0].row;
}
catch(err) {
;
}
$(".google-visualization-tooltip-item-list li:eq(0)").css("font-weight", "bold");
$(".google-visualization-tooltip-item-list li:eq(1)").html(tooltip[sliceid]).css("font-family", "Arial");
}
google.visualization.events.addListener(chart, 'onmousedown', eventHandler);
google.visualization.events.addListener(chart, 'onmouseover', eventHandler);
chart.draw(data, options);
}
</script>
HTML for above script
<div id="piechart"></div>
Css for above code snippet
<style>
#piechart {
top: 0;
left: 0;
width:100%;
height:100%;
}
.google-visualization-tooltip{
display:table;
}
g{
cursor:pointer;
}
</style>