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>
Related
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
};
I want to trigger to different tooltips on a single column chart, one on hover and another on bar select.
How can i solve it ?
I went through the following links but couldn't solve it.
Show multiple tooltips in Google Charts
Google charts to show multiple tooltip
How to show/hide google chart's tooltip programatically?
ToolTip only shows on "Click"- google charts
out of the box, google chart does not offer this functionality.
you will need to turn off the default tooltips,
tooltip: {
trigger: 'none'
}
and add your own custom tooltips.
you can use chart events to determine which tooltip to show.
('select', 'onmouseover', 'onmouseout')
to position your custom tooltip,
you can use chart method --> getChartLayoutInterface
the interface has a method for --> getBoundingBox
which returns the position of a chart element,
just pass the id of the element, such as a chart column.
chart column id's take the form as --> bar#0#0
where the first 0 is the series number,
and the second 0 is the row number.
something to think about is how to handle collisions.
meaning, what are you going to show when a column is selected, then hovered.
or a column is selected and another column is hovered, etc...
see following working snippet for an example of how to accomplish...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['City', '2010 Population',],
['New York City, NY', 8175000],
['Los Angeles, CA', 3792000],
['Chicago, IL', 2695000],
['Houston, TX', 2099000],
['Philadelphia, PA', 1526000]
]);
var options = {
title: 'Population of Largest U.S. Cities',
chartArea: {width: '50%'},
hAxis: {
title: 'Total Population',
minValue: 0
},
vAxis: {
title: 'City'
},
tooltip: {
trigger: 'none'
}
};
var chart = new google.visualization.ColumnChart($('#chart_div').get(0));
var chartLayout;
var selection;
google.visualization.events.addListener(chart, 'ready', function () {
chartLayout = chart.getChartLayoutInterface();
});
google.visualization.events.addListener(chart, 'select', function () {
selection = getSelection();
if (selection.row !== null) {
hideTooltip('tooltip-hover');
showTooltip(selection, 'tooltip-select');
} else {
hideTooltip('tooltip-select');
}
});
google.visualization.events.addListener(chart, 'onmouseover', function (sender) {
selection = getSelection();
if ((sender.row !== null) && (selection.row !== sender.row)) {
showTooltip(sender, 'tooltip-hover');
}
});
google.visualization.events.addListener(chart, 'onmouseout', function (sender) {
selection = getSelection();
if ((sender.row !== null) && (selection.row !== sender.row)) {
hideTooltip('tooltip-hover');
}
});
function showTooltip(sender, tooltip) {
// get position of bar
var tooltipBounds = chartLayout.getBoundingBox('bar#' + (sender.column - 1) + '#' + sender.row);
// set values
$('#' + tooltip + ' .series-name').html(data.getColumnLabel(sender.column));
$('#' + tooltip + ' .series-x').html(data.getFormattedValue(sender.row, 0));
$('#' + tooltip + ' .series-y').html(data.getFormattedValue(sender.row, sender.column));
// set position
$('#' + tooltip).css({
left: tooltipBounds.left + 'px',
top: (tooltipBounds.top - $('#' + tooltip).outerHeight(true)) + 'px'
});
// show
$('#' + tooltip).addClass('shown');
$('#' + tooltip).removeClass('hidden');
}
function hideTooltip(tooltip) {
// hide
$('#' + tooltip).addClass('hidden');
$('#' + tooltip).removeClass('shown');
}
function getSelection() {
selection = chart.getSelection();
if (selection.length > 0) {
return selection[0];
} else {
return {row: null, column: null};
}
}
chart.draw(data, options);
});
.ggl-tooltip {
background-color: #ffffff;
border: 1px solid #E0E0E0;
font-size: 10pt;
padding: 8px 8px 8px 8px;
position: absolute;
}
.ggl-tooltip div {
margin-top: 4px;
}
.bold {
font-weight: bold;
}
.hidden {
display: none;
visibility: hidden;
}
.shown {
display: inline-block;
}
#tooltip-hover {
color: blue;
}
#tooltip-select {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='https://www.gstatic.com/charts/loader.js'></script>
<div id="chart_div"></div>
<div id="tooltip-hover" class="ggl-tooltip hidden">
<div><span class="series-name bold"></span></div>
<div>
<span class="series-x bold"></span>:
<span class="series-y"></span>
</div>
</div>
<div id="tooltip-select" class="ggl-tooltip hidden">
<div><span class="series-name bold"></span></div>
<div>
<span class="series-x bold"></span>:
<span class="series-y"></span>
</div>
</div>
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
Chart is loading fine but I'm unable to autorefresh this chart, tried setInterval(drawChart, 10000); and is not working. Did I place the interval in the wrong position? function is drawChart.
function drawChart(candlestickChartDataOptions, candlestickChartData, chart_id) {
var data = google.visualization.arrayToDataTable(candlestickChartData, true);
var options = {
chartArea: {
left: 40,
top: 20,
width: "100%",
height: "70%"
},
legend:"none",
title:candlestickChartDataOptions.currency1+" price in "+candlestickChartDataOptions.currency2,
bar: { groupWidth: "70%" ,
}, // sets space between bars
candlestick: {
fallingColor: { strokeWidth: 0, fill: "#a52714" }, // red
risingColor: { strokeWidth: 0, fill: "#0f9d58" }, // green
}
};
var chart = new google.visualization.CandlestickChart(document.getElementById(chart_id));
chart.draw(data, options);
}
jQuery( document ).ready(function() {
jQuery( "select#chart_period_'.$chart_id.'" ).change(function() {
setCandlestickPeriod(candlestickChartDataOptions_'.$chart_id.', jQuery(this).val());
candlestickLoadData(candlestickChartDataOptions_'.$chart_id.', "'.$chart_id.'");
});
drawChart();
setInterval(drawChart, 10000);
});
</script>
<div id="<?php echo $chart_id; ?>"></div>
Also tried this and is not working too, the $chart_id is correct:
<script>
setInterval(function(){
$("<?php echo $chart_id; ?>").load(document.URL + " <?php echo
$chart_id; ?>");
}, 10000)
</script>
What went wrong? Please help thanks.
I need your help to show charts while rendering pdf using ABCpdf.
Here is a result, what is in browser and what is on pdf:
Actually as it looks good on html, I think the problem is in rendering pdf. Here is the code I am using to create pdf:
var theDoc = new Doc();
theDoc.HtmlOptions.Timeout = 10000;
theDoc.HtmlOptions.UseScript = true;
theDoc.HtmlOptions.PageCacheEnabled = false;
theDoc.HtmlOptions.OnLoadScript = "(function(){ " +
"window.ABCpdf_go = false; " +
"onLoad(); " +
"window.ABCpdf_go = true; })();";
theDoc.AddImageUrl("file:///E:/development/temp/test(1).html");
theDoc.Save(string.Format("output-{0}.pdf", DateTime.Now.Ticks));
theDoc.Clear();
And here is my html page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
var options = {
'title': 'How Much Pizza I Ate Last Night',
'width': 400,
'height': 300
};
var chart = new google.visualization.PieChart(document.getElementById('chart-div'));
google.visualization.events.addListener(chart, 'ready', function () { onChartRenderReady(chart);});
chart.draw(data, options);
}
function addText(text) {
var h = document.createElement('h1');
var t = document.createTextNode(text);
h.appendChild(t);
document.body.appendChild(h);
}
function onDOMContentLoaded() {
addText('From onDOMContentLoaded event');
drawChart();
}
function onLoad() {
addText('From onLoad event');
drawChart();
addText('Finished drawing chart');
}
function onChartRenderReady(chart) {
addText('From onChartRenderReady event');
var imageDiv = document.getElementById('chart-image');
imageDiv.innerHTML = '<img src="' + chart.getImageURI() + '">';
addText('Added image');
// ABCpdf_RenderComplete();
}
function test() {
addText('test');
}
function ABCpdf_RenderWait_Dummy() {
addText('ABCpdf_RenderWait_Dummy');
}
function ABCpdf_RenderComplete_Dummy() {
addText('ABCpdf_RenderComplete_Dummy');
}
google.load('visualization', '1.0', { 'packages': ['corechart'] });
document.addEventListener("DOMContentLoaded", onDOMContentLoaded);
window.onload = onLoad;
</script>
<style>
#chart {
height: 300px;
width: 400px;
border: 1px solid black;
}
</style>
</head>
<body>
<div id="chart-image"></div>
<form id="chart">
<div id="chart-div"></div>
</form>
<h3>Static text (should be always present)</h3>
</body>
</html>
Will be glad for any help.
The issue was only in Gecko Engine. After adding theDoc.HtmlOptions.Engine = EngineType.Gecko; the issue was solved