Google-chart trendline not showing - google-visualization

Google-chart trend-line not showing. Tried to put the code in vAxis, hAxis and only in options but no luck. I know that the first column must be a number or date and so on and my first column is a date.
<script type="text/javascript">
data.sort([{column: 0}]);
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'Sum'],
<?php while($row = mysqli_fetch_assoc($result)) { ?>
[<?php echo $row['date'] ?>, <?php echo $row['col2'] ?> ],
<?php } ?>
]);
var options = {
legend: { position: 'bottom' },
title: 'Sum per day',
hAxis : { textStyle : { fontSize: 10 } },
vAxis: { viewWindowMode: 'explicit', viewWindow: { min: 0 } },
trendlines: { 0: {} }
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
}
</script>

when loading the data, the first column needs to be converted from a string to a date.
place the value from php in quotes and inside a date constructor.
e.g.
[new Date('<?php echo $row['date'] ?>'), <?php echo $row['col2'] ?> ],
if you still have problems with the squiggly line,
sort the data before drawing...
data.sort([{column: 0}]);
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);

Related

How to give api count and date value to google line chart?

I am making a simple web counter using count api. I am good in getting the counts. Now, I'm making a google line chart to show count value with the date in graph form. So, please help me how to set the date and count data in drawChart() function to get the count as per the date. And the graph should have 5 days of count. How to achieve this solution. Sincere Thanks in Advance!
const counter = document.getElementById('count');
updateVisitCount();
function updateVisitCount() {
fetch('https://api.countapi.xyz/update/demo/sample/?amount=1').then(res => res.json())
.then(res => {
counter.innerHTML = res.value;
});
}
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'Number of Site Visits'],
]);
var options = {
title: 'Site Visits',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
That's working.
var counters=[
['string', 'value'],
];
setInterval(()=>{
fetch('https://api.countapi.xyz/update/demo/sample/?amount=1').then(res => res.json())
.then(res => {
var dt = new Date();
var secs = dt.getSeconds()
counters.push(
[secs,res.value]
)
if(counters.length>3){
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
}
});
},1000);
function drawChart() {
var data = new google.visualization.arrayToDataTable(counters);
var options = {
title: 'Site Visits',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

Google charts Axis showing disordered values and columns are suming

The axis is showing disordered values and the columns are summing I don't know why.
The data is in percentage although it could be more then 100% if the achievement is superior to target.
This is my code (before it there is one Foreach):
$vttCloud = number_format((($CountryCloudAchieved)*pow(($CountryTarget*0.25 ), -1))*100, 2, ",", ".");
$vtt = number_format((($CountryAchieved)*pow(($CountryTarget), -1))*100, 2, ",", ".");
if ($vttCloud == 0 && $vtt == 0) {} else {
?>
['<?php echo $Country; ?>', '<?php echo $vtt; ?>', '<?php echo $vttCloud; ?>'],
<?php } } ?>
use numbers instead of strings for columns 1 & 2 (lose the single quotes)...
['<?php echo $Country; ?>', <?php echo $vtt; ?>, <?php echo $vttCloud; ?>],
strange it will let you draw a chart with strings as values,
see following two examples, one with numbers, the other with strings...
google.charts.load('current', {
callback: function () {
drawChartGood();
drawChartBad();
},
packages:['bar']
});
function drawChartGood() {
var dataTable = google.visualization.arrayToDataTable([
['Country', 'vtt', 'vttCloud'],
['Czech Republic', 50, 60],
['Italy', 75, 80],
['Croatia', 28, 40]
]);
var options = {
bars: 'horizontal'
};
var chart = new google.charts.Bar(document.getElementById('chart_good'));
chart.draw(dataTable, google.charts.Bar.convertOptions(options));
}
function drawChartBad() {
var dataTable = google.visualization.arrayToDataTable([
['Country', 'vtt', 'vttCloud'],
['Czech Republic', '50', '60'],
['Italy', '75', '80'],
['Croatia', '28', '40']
]);
var options = {
bars: 'horizontal'
};
var chart = new google.charts.Bar(document.getElementById('chart_bad'));
chart.draw(dataTable, google.charts.Bar.convertOptions(options));
}
div {
padding-bottom: 24px;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>Numbers</div>
<div id="chart_good"></div>
<div>Strings</div>
<div id="chart_bad"></div>

Hide text from Google GeoChart tooltip

I have a Google Geochart that is connected to a Google Spreadsheet. The aim of the chart is to show different categories of universities in our state and their locations. I have assigned values in the spreadsheet in order to have the appropriate marker color for the map to denote the categories.
My problem is that the text denoting the type (a number) is showing in the tooltip. (Example: tooltip shows "ABC University Type 3." I need to either hide this text, or create a string based on conditional logic so that, for example, Type 3 translates to "XYZ System" in the tooltip. Which do you think is the better way to do it, and can you provide guidance as to how to do this?
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
google.charts.load('current', { 'packages': ['geochart'] });
google.charts.setOnLoadCallback(drawMap);
function drawMap() {
var query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1m3ujxzPQJh3haReNDzGGF73Mh6-u6HxyCVPK_5MK2hw/gviz/tq?sheet=Sheet3");
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {var data = response.getDataTable();
var options = {
//showTip: true,
mapType: 'styledMap',
useMapTypeControl: true,
resolution: 'provinces',
//displayMode: 'text',
//magnifyingGlass: {'enable': true, 'zoomFactor': '7'},
region: 'US-KY',
keepAspectRatio: true,
legend: 'none',
sizeAxis: { minValue: 1, maxValue: 3, minSize: 10, maxSize: 10 },
colorAxis: {colors: ['green', 'blue', 'purple'], values: [1, 2, 3]},
markerOpacity: 0.75,
tooltip: {showColorCode: false, isHTML: true, textStyle:{fontSize: 21}},
dataMode: 'markers'
};
var map = new google.visualization.GeoChart(document.getElementById('chart_div'));
map.draw(data, options);
};
</script>
<style type="text/css">
html, body {height: 100%;}
#chart_div {width: 100%; height: 100%;}
</style>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
You can use the DataView Class to change the formatted value of the Type column.
For instance, the value of the Type column in the DataTable looks like this...
{"v":3.0,"f":"3"}
With the DataView, change it to this...
{"v":3.0,"f":"XYZ System"}
We can also remove the column Label, to avoid seeing it in the tooltip.
See following example...
google.charts.load('current', {
callback: drawMap,
packages: ['geochart']
});
function drawMap() {
var query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1m3ujxzPQJh3haReNDzGGF73Mh6-u6HxyCVPK_5MK2hw/gviz/tq?sheet=Sheet3");
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
var data = response.getDataTable();
// setup school type array
var schoolTypes = [
'ABC System',
'LMO System',
'XYZ System'
];
// create DataView from DataTable
var view = new google.visualization.DataView(data);
// set view columns, keep first three columns
// use calculated column for Type
view.setColumns([0, 1, 2, {
type: 'number',
label: '',
calc: function (dataTable, rowIndex) {
return {
v: dataTable.getValue(rowIndex, 3),
// get school type from array
f: schoolTypes[dataTable.getValue(rowIndex, 3) - 1]
}
}
}]);
var options = {
//showTip: true,
mapType: 'styledMap',
useMapTypeControl: true,
resolution: 'provinces',
//displayMode: 'text',
//magnifyingGlass: {'enable': true, 'zoomFactor': '7'},
region: 'US-KY',
keepAspectRatio: true,
legend: 'none',
sizeAxis: { minValue: 1, maxValue: 3, minSize: 10, maxSize: 10 },
colorAxis: {colors: ['green', 'blue', 'purple'], values: [1, 2, 3]},
markerOpacity: 0.75,
tooltip: {showColorCode: false, isHTML: true, textStyle:{fontSize: 21}},
dataMode: 'markers'
};
var map = new google.visualization.GeoChart(document.getElementById('chart_div'));
map.draw(view, options);
};
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
ALSO -- Recommend including loader.js and jsapi only once per page

Save graph as image after click link full script

I have this code
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.2.js"></script>
<script type="text/javascript" src="js/chart-js/Chart.js"></script>
<script type="text/javascript">
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
}
];
$(document).ready(
function () {
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Pie(data);
document.getElementById("canvas_link").src = document.getElementById("myChart").toDataURL();
}
);
</script>
</head>
<body>
<p>save as image</p>
<canvas id="myChart" width="400" height="400"></canvas>
<p>export to pdf</p>
</body>
I need create pdf export and add into image with gener graph. Berofe I must save render image. I try use method .toBase64Image() but I dont know have can I start.
My proceed
create canvas_link (.toDataUrl). After click save as image I can greate and upload image to server. Then I can generate pdf export (across mPDF) and to add imageto into export. This i can create, but I dont know create and upload image of graph to server.
I need more examples from http://www.chartjs.org/docs/
in that case you don't need to upload as an image.
you could put the result of the call to toDataUrl function in the value of a hidden field and send it in a form (with an iframe as target) or by an ajax call
use the following options in the chart
//new options var
var options = {
bezierCurve : false,
//animation: false
onAnimationComplete: done
};
//your code with a little modification
$(document).ready(
function () {
var ctx = document.getElementById("myChart").getContext("2d");
//use the previously defined "options" here!!!
var myNewChart = new Chart(ctx).Pie(data, options);
}
);
//callback function, called when the pie ends his animation
function done(){
//this part of your code was moved here to avoid that store an empty image
document.getElementById("canvas_link").src = document.getElementById("myChart").toDataURL();
var postdata={
file: document.getElementById("myChart").toDataURL()
}
$.post( "store.php", postdata)
.done(function( ret ) {
console.log( "Data status: Loaded successfully ");
})
.fail(function( ret ) {
console.log( "Data status: error ");
})
;
}
Reference: http://api.jquery.com/jquery.post/
in php you can handle the content in this way
// file: store.php
// Interpret data uri
$uriPhp = 'data://' . substr($file, 5);
// Get content
$binary = file_get_contents($uriPhp);
$file = 'uploads/charts/'. time() .'.png';
// Save image
file_put_contents($file, $binary);
Reference: https://github.com/nnnick/Chart.js/issues/99#issuecomment-75359927
As per the documentation, you can print or save graph by API calls;
Example
var chart = new CanvasJS.Chart("chartContainer", {
theme: "theme2",
title:{
text: "Print Chart using print() method"
},
data: [
{
type: "column",
dataPoints: [
{ label: "apple", y: 10 },
{ label: "orange", y: 15 },
{ label: "banana", y: 25 },
{ label: "mango", y: 30 },
{ label: "grape", y: 28 }
]
}
]
});
chart.render();
document.getElementById("printChart").addEventListener("click",function(){
chart.print();
//chart.exportChart({format: "jpg"});
});

Combining two types of Category Filter in Google Charts API

I wanted to enable users to filter the results being displayed on the chart. Google API provides CategoryFilter which enforces filtering by rows. Here is my code which works perfectly fine
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['controls']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var countryPicker = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'negeri',
dataTable: data,
options: {
filterColumnLabel: 'Negeri',
ui: {
labelStacking: 'vertical',
allowTyping: false,
allowMultiple: true
}
},
// Define an initial state, i.e. a set of metrics to be initially selected.
state: {'selectedValues': ['Kedah', 'Johor']}
});
var chart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
options: {
title: 'Statistik Negeri vs. Kategori Sukan',
width: 1000,
height: 1000,
hAxis: {title: 'Negeri', titleTextStyle: {color: 'blue'}},
vAxis: {title: 'Jumlah Kategori', titleTextStyle: {color: 'blue'}}
}
});
// Create the dashboard.
new google.visualization.Dashboard(document.getElementById('dashboard')).
// Configure the controls so that:
// - the 'Country' selection drives the 'Region' one,
// - the 'Region' selection drives the 'City' one,
// - and finally the 'City' output drives the chart
bind(countryPicker, chart).
// Draw the dashboard
draw(data);
}
</script>
</head>
<body>
<div id="dashboard">
<div id="negeri"></div>
<div id="chart_div"></div>
</div>
</body>
</html>
However in my datatable, I would also want to filter by columns. These two types of filtering should work together. (dependent; by bind() function). I have referred to #asgallant http://jsfiddle.net/asgallant/WaUu2/ and that is the feature that I wanted to combine with.
How can I possibly combine them? I have tried combining setChartView() by #asgallant with google's dashboard() but it's not working.
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['controls']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var columnsTable = new google.visualization.DataTable();
columnsTable.addColumn('number', 'colIndex');
columnsTable.addColumn('string', 'colLabel');
var initState= {selectedValues: []};
// put the columns into this data table (skip column 0)
for (var i = 1; i < data.getNumberOfColumns(); i++) {
columnsTable.addRow([i, data.getColumnLabel(i)]);
// you can comment out this next line if you want to have a default selection other than the whole list
initState.selectedValues.push(data.getColumnLabel(i));
}
var countryPicker = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'negeri',
dataTable: data,
options: {
filterColumnLabel: 'Negeri',
ui: {
labelStacking: 'vertical',
allowTyping: false,
allowMultiple: true
}
},
// Define an initial state, i.e. a set of metrics to be initially selected.
state: {'selectedValues': ['Kedah', 'Johor']}
});
var columnFilter = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'colFilter_div',
dataTable: columnsTable,
options: {
filterColumnLabel: 'colLabel',
ui: {
label: 'Kategori Sukan',
allowTyping: false,
allowMultiple: true,
allowNone: false,
selectedValuesLayout: 'belowStacked'
}
},
state: initState
});
var chart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
options: {
title: 'Statistik Negeri vs. Kategori Sukan',
width: 1000,
height: 1000,
hAxis: {title: 'Negeri', titleTextStyle: {color: 'blue'}},
vAxis: {title: 'Jumlah Kategori', titleTextStyle: {color: 'blue'}}
}
});
// Create the dashboard.
new google.visualization.Dashboard(document.getElementById('dashboard')).
// Configure the controls so that:
// - the 'Country' selection drives the 'Region' one,
// - the 'Region' selection drives the 'City' one,
// - and finally the 'City' output drives the chart
bind(countryPicker, columnFilter).
bind(columnFilter, chart).
// Draw the dashboard
draw(data);
}
</script>
</head>
<body>
<div id="dashboard">
<div id="negeri"></div>
<div id="chart_div"></div>
</div>
</body>
</html>
You want to bind your countryPicker filter to the chart as normal, but do not bind the columnFilter control to anything - the setChartView function handles everything for the columnFilter. You need to tweak a couple other lines to make it work with a dashboard, but nothing major. This is what it should look like:
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var columnsTable = new google.visualization.DataTable();
columnsTable.addColumn('number', 'colIndex');
columnsTable.addColumn('string', 'colLabel');
var initState= {selectedValues: []};
// put the columns into this data table (skip column 0)
for (var i = 1; i < data.getNumberOfColumns(); i++) {
columnsTable.addRow([i, data.getColumnLabel(i)]);
// you can comment out this next line if you want to have a default selection other than the whole list
initState.selectedValues.push(data.getColumnLabel(i));
}
var countryPicker = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'negeri',
dataTable: data,
options: {
filterColumnLabel: 'Negeri',
ui: {
labelStacking: 'vertical',
allowTyping: false,
allowMultiple: true
}
},
// Define an initial state, i.e. a set of metrics to be initially selected.
state: {'selectedValues': ['Kedah', 'Johor']}
});
var columnFilter = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'colFilter_div',
dataTable: columnsTable,
options: {
filterColumnLabel: 'colLabel',
ui: {
label: 'Kategori Sukan',
allowTyping: false,
allowMultiple: true,
allowNone: false,
selectedValuesLayout: 'belowStacked'
}
},
state: initState
});
var chart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
options: {
title: 'Statistik Negeri vs. Kategori Sukan',
width: 1000,
height: 1000,
hAxis: {title: 'Negeri', titleTextStyle: {color: 'blue'}},
vAxis: {title: 'Jumlah Kategori', titleTextStyle: {color: 'blue'}}
}
});
// Create the dashboard.
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard')).
bind(countryPicker, chart);
function setChartView () {
var state = columnFilter.getState();
var row;
var view = {
columns: [0]
};
for (var i = 0; i < state.selectedValues.length; i++) {
row = columnsTable.getFilteredRows([{column: 1, value: state.selectedValues[i]}])[0];
view.columns.push(columnsTable.getValue(row, 0));
}
// sort the indices into their original order
view.columns.sort(function (a, b) {
return (a - b);
});
chart.setView(view);
chart.draw();
}
google.visualization.events.addListener(columnFilter, 'statechange', setChartView);
var runOnce = google.visualization.events.addListener(dashboard, 'ready', function () {
google.visualization.events.removeListener(runOnce);
setChartView();
});
columnFilter.draw();
dashboard.draw(data);
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});