I need advice on this matter, I tried to convert this sample code (https://developers.google.com/chart/interactive/docs/php_example?csw=1) from pie chart to google stacked bar chart which looks like this
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMultSeries);
function drawMultSeries() {
var data = google.visualization.arrayToDataTable([
['Genre',
/*Agriculture 4*/
'Agriculture (Plants)',
'Agriculture (Livestock)',
'Agriculture (Aquaculture)',
'Others Agriculture',
/*Beach 4*/
'Sandy Beach',
'Stoney Beach',
'Buddy Beach',
'Others Beach',
/*Shophouses 7*/
'Shophouses (Commercial )',
'Shophouses (Office)',
'Shophouses (Commercial & Residential)',
'Shophouses (Commercial & Office)',
'Shophouses (Commercial & Residential & Office)',
'Shophouses (Hotel/Inn/Budget Hotel/Lodging)',
'Others Shophouses',
{ role: 'annotation' } ],
['Agriculture',
/*Agriculture 4*/10,24,20,32,
/*Beach 4*/0,0,0,0,
/*Shophouses 7*/ 0,0,0,0,0,0,0,
''],
['Beach',
/*Agriculture 4*/0,0,0,0,
/*Beach 4*/10,20,30,40,
/*Shophouses 7*/ 0,0,0,0,0,0,0,
''],
['Shophouses',
/*Agriculture 4*/0,0,0,0,
/*Beach 4*/0,0,0,0,
/*Shophouses 7*/ 10,20,30,20,40,60,20,
'']
]);
var options = {
width: 800,
height: 400,
legend: { position: 'bottom', maxLines: 2 },
bar: { groupWidth: '50%' },
isStacked: 'percent'
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I encounter problem when replacing the var data = new google.visualization.DataTable(jsonData); with var data = google.visualization.arrayToDataTable();
The modified file from sample code is in the attachment.
Related
my sql query to fetch state count and state name that give me count and name of the state.
my problem is that i wanted to display multiple markers on google map from database. I need to display the data on click of marker on info window at google map im trying following code.
I'm not able to understand how to add loop in data.addRows.
or please let me know where I'm doing wrong
$sql = "SELECT `state`, COUNT(DISTINCT `sr_no`) AS `stateno`
FROM `Mystate` GROUP BY `state`";
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'packages': ['map'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': 'API_KEY'
});
google.charts.setOnLoadCallback(drawMap);
function drawMap () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Address');
data.addColumn('string', 'Location');
data.addColumn('string', 'Marker')
data.addRows([
['Mumbai, Maharashtra', 'India', 'blue' ],
['Pune, Maharashtra', 'India', 'green']
]);
var url = 'https://icons.iconarchive.com/icons/icons-land/vista-map-markers/48/';
var options = {
center: { lat: 20.5937, lng: 78.9629 },
zoomLevel: 5,
showTooltip: true,
showInfoWindow: true,
useMapTypeControl: true,
icons: {
blue: {
normal: url + 'Map-Marker-Ball-Azure-icon.png',
selected: url + 'Map-Marker-Ball-Right-Azure-icon.png'
},
green: {
normal: url + 'Map-Marker-Push-Pin-1-Chartreuse-icon.png',
selected: url + 'Map-Marker-Push-Pin-1-Right-Chartreuse-icon.png'
},
pink: {
normal: url + 'Map-Marker-Ball-Pink-icon.png',
selected: url + 'Map-Marker-Ball-Right-Pink-icon.png'
}
}
};
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, options);
}
</script>
</head>
<body>
<div id="map_div" style="height: 600px; width: 900px"></div>
</body>
</html>
It is not clear how you hope to select the colour of the marker, nor what you actually do with the stateno from the SQL query. That said, the JSON deata in the following is from one of my old databases and was used to emulate what your query might return. The actual task of processing this recordset and adding the data to the dataTable is done with an Object.keys( json ).forEach loop.
ie:
Object.keys( json ).forEach( key=>{
let obj=json[ key ];
data.addRow([
obj.state, 'India', 'green'
]);
})
The full, working example with a hardcoded valud of green for the marker. I would suggest that this colour could be determined by the stateno data as that is not used but nothing in the above supports that. If that were the case a simple lookup of the stateno number against some sort of matrix of value/colour could be done.
I should possibly warn that running and testing this multiple times could lead to charges being raised against your apikey because of the need for each marker location needing to be geocoded in order to find the location.
<html>
<head>
<script src='https://www.gstatic.com/charts/loader.js'></script>
<script>
const json=[
{
"state":"Andaman and Nicobar Islands",
"stateno":"1"
},
{
"state":"Andhra Pradesh",
"stateno":"104"
},
{
"state":"Arunachal Pradesh",
"stateno":"1"
},
{
"state":"Assam",
"stateno":"15"
},
{
"state":"Bihar",
"stateno":"46"
},
{
"state":"Chandigarh",
"stateno":"1"
},
{
"state":"Chhattisgarh",
"stateno":"12"
},
{
"state":"Delhi",
"stateno":"29"
},
{
"state":"Goa",
"stateno":"3"
},
{
"state":"Gujarat",
"stateno":"63"
},
{
"state":"Haryana",
"stateno":"26"
},
{
"state":"Himachal Pradesh",
"stateno":"1"
},
{
"state":"Jammu and Kashmir",
"stateno":"8"
},
{
"state":"Jharkhand",
"stateno":"23"
},
{
"state":"Karnataka",
"stateno":"65"
},
{
"state":"Kerala",
"stateno":"32"
},
{
"state":"Madhya Pradesh",
"stateno":"53"
},
{
"state":"Maharashtra",
"stateno":"90"
},
{
"state":"Manipur",
"stateno":"1"
},
{
"state":"Meghalaya",
"stateno":"2"
},
{
"state":"Mizoram",
"stateno":"2"
},
{
"state":"Nagaland",
"stateno":"3"
},
{
"state":"Orissa",
"stateno":"22"
},
{
"state":"Pondicherry",
"stateno":"3"
},
{
"state":"Punjab",
"stateno":"34"
},
{
"state":"Rajasthan",
"stateno":"50"
},
{
"state":"Tamil Nadu",
"stateno":"85"
},
{
"state":"Tripura",
"stateno":"3"
},
{
"state":"Uttar Pradesh",
"stateno":"119"
},
{
"state":"West Bengal",
"stateno":"93"
}
];
google.charts.load('current', {
'packages': ['map'],
'mapsApiKey': 'AIzaSy..................04......tA'
});
google.charts.setOnLoadCallback(drawMap);
function drawMap () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Address');
data.addColumn('string', 'Location');
data.addColumn('string', 'Marker');
/*
data.addRows([
['Mumbai, Maharashtra', 'India', 'blue' ],
['Pune, Maharashtra', 'India', 'green']
]);
*/
Object.keys( json ).forEach( key=>{
let obj=json[ key ];
data.addRow([
obj.state, 'India', 'green'
]);
})
var url = 'https://icons.iconarchive.com/icons/icons-land/vista-map-markers/48/';
var options = {
center: { lat: 20.5937, lng: 78.9629 },
zoomLevel: 5,
showTooltip: true,
showInfoWindow: true,
useMapTypeControl: true,
icons: {
blue: {
normal: url + 'Map-Marker-Ball-Azure-icon.png',
selected: url + 'Map-Marker-Ball-Right-Azure-icon.png'
},
green: {
normal: url + 'Map-Marker-Push-Pin-1-Chartreuse-icon.png',
selected: url + 'Map-Marker-Push-Pin-1-Right-Chartreuse-icon.png'
},
pink: {
normal: url + 'Map-Marker-Ball-Pink-icon.png',
selected: url + 'Map-Marker-Ball-Right-Pink-icon.png'
}
}
};
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, options);
}
</script>
</head>
<body>
<div id='map_div' style='height: 600px; width: 900px'></div>
</body>
</html>
update
Following on from comments about infoWindows etc I modified the working code I had to perform the lookup and return a different colour icon based upon arbitrary figures ( edit as appropriate if applicable ) and modified the data being added to the dataTable so that the 2nd argument contains the name & count - when the marker is clicked that will be displayed in the tooltip/infoWindow
const matrix={
0:'blue',
30:'green',
75:'pink'
};
const lookup=(i)=>{
let icon=false;
Object.keys( matrix ).forEach( key=>{
if( i > key ) icon=matrix[ key ];
});
return icon
};
Object.keys( json ).forEach( key=>{
let obj=json[ key ];
let icon=lookup( obj.stateno );
data.addRow([
obj.state, `${obj.state} - Count: ${obj.stateno}`, icon
])
});
I have a chart like this (drawn by google charts)
the line is generated by google with option of Linear trendlines
image
code
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Diameter', 'Age'],
[8, 37], [4, 19.5], [11, 52], [4, 22], [3, 16.5], [6.5, 32.8], [14, 72]]);
var options = {
title: 'Age of sugar maples vs. trunk diameter, in inches',
hAxis: {title: 'Diameter'},
vAxis: {title: 'Age'},
legend: 'none',
trendlines: { 0: {} } // Draw a trendline for data series 0.
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
how to know the equation of this line?
adding the trendline to the legend will reveal the equation...
trendlines: {
0: {
visibleInLegend: true
}
}
you can remove the series from the legend, if so desired...
series: {
0: {
visibleInLegend: false
}
},
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Diameter', 'Age'],
[8, 37], [4, 19.5], [11, 52], [4, 22], [3, 16.5], [6.5, 32.8], [14, 72]]);
var options = {
title: 'Age of sugar maples vs. trunk diameter, in inches',
hAxis: {title: 'Diameter'},
vAxis: {title: 'Age'},
legend: {
alignment: 'end',
position: 'top'
},
series: {
0: {
visibleInLegend: false
}
},
trendlines: {
0: {
visibleInLegend: true
}
}
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
once the equation has been added to the legend,
you can get the value from the <text> element used to draw the legend marker
but need to wait on the 'ready' event first,
to know the chart has finished drawing
also, you will need a way to determine the legend marker <text> element
from the other labels, such as the chart title
in this example, both the title and the legend marker
have an attribute text-anchor with a value of 'start'
text-anchor could change depending the legend's alignment and position
the font color (fill) is used to separate the title from the legend marker...
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Diameter', 'Age'],
[8, 37], [4, 19.5], [11, 52], [4, 22], [3, 16.5], [6.5, 32.8], [14, 72]]);
var options = {
title: 'Age of sugar maples vs. trunk diameter, in inches',
hAxis: {title: 'Diameter'},
vAxis: {title: 'Age'},
legend: {
alignment: 'end',
position: 'top'
},
series: {
0: {
visibleInLegend: false
}
},
trendlines: {
0: {
visibleInLegend: true
}
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ScatterChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var equation = $('text[text-anchor="start"][fill="#222222"]').text();
console.log(equation);
});
chart.draw(data, options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
This works for me:
var container = document.getElementById('chart_div');
var chart = new google.visualization.ScatterChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
console.log(chart.Zl().jp[1].text);
});
chart.draw(data, options);
chart.Zl().jp looks like this:
[
{
"id": "",
"text": "Age",
"brush": "{\"fill\":\"#3366cc\",\"fillOpacity\":1,\"stroke\":\"none\",\"strokeWidth\":1,\"strokeOpacity\":1,\"strokeDashStyle\":\"solid\",\"rx\":null,\"ry\":null,\"gradient\":null,\"pattern\":null,\"shadow\":null}",
"index": 0,
"ja": false
},
{
"id": "_trendline",
"text": "y = 4.885 * x + 0.73",
"brush": "{\"fill\":\"#3366cc\",\"fillOpacity\":0.5,\"stroke\":\"none\",\"strokeWidth\":1,\"strokeOpacity\":1,\"strokeDashStyle\":\"solid\",\"rx\":null,\"ry\":null,\"gradient\":null,\"pattern\":null,\"shadow\":null}",
"index": 1,
"ja": true
}
]
so for each series there will be two objects, one for series and second for trendline, so if for example you have two trendlines you can get the second equation with chart.Zl().jp[3].text
I'm working on a dual Y-axis linechart that is to have both height and weight on the Y-axes with the date displaying on the X-axis:
I'm pulling the data from my MYSQL database and encoding it into json and the passing it to my function that draws the chart as shown:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Height');
data.addColumn('number', 'Weight');
data.addRows([
<?php
$chart_info = $db->prepare("SELECT `height`, `weight`, `date_captured` FROM `child_results_capture` ");
$chart_info->execute();
$result = $chart_info->fetchAll(PDO::FETCH_ASSOC);
$chart_data = '';
foreach($result as $value)
{
$chart_data.="['".$value['date_captured']."',".$value['height'].",".$value['weight']."],";
// var_dump($chart_data);exit;
// echo $chart_data;
}
echo $chart_data;
?>
]);
var options = {
title: 'Height-Weight graph',
width: 900,
height: 500,
series: {
0: {axis: 'Height'},
1: {axis: 'Weight'}
},
axes: {
y: {
Height: {label: 'Height (cm)'},
Weight: {label: 'Weight (kg)'}
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('graph_chart'));
chart.draw(data, options);
}
</script>
<div id="graph_chart"></div>
The Json returned from my php bit looks like this:
['2016-07-27',51,3.4],['2016-08-03',52,4],['2016-08-10',53,5],['2016-08-17',54,6],['2016-08-24',55,7],['2016-08-31',56,8],
And my output looks like this:
As shown above, I only get one Y-axis(for the height) and my chart axes are not labelled with the corresponding names
Will appreciate being pointed in the right direction
the specific configuration options used in the question to build the Dual-Y Chart
are for Material charts only --> google.charts.Line
var optionsMatl = {
title: 'Height-Weight graph',
width: 900,
height: 500,
series: {
0: {axis: 'Height'},
1: {axis: 'Weight'}
},
axes: {
y: {
Height: {label: 'Height (cm)'},
Weight: {label: 'Weight (kg)'}
}
}
};
a different set of options is needed to build a Dual-Y Chart
in a Classic chart --> google.visualization.LineChart
var optionsCore = {
title: 'Height-Weight graph',
width: 900,
height: 500,
series: {
1: {
targetAxisIndex: 1
}
},
vAxes: {
0: {
title: 'Height (cm)'
},
1: {
title: 'Weight (kg)'
}
},
theme: 'material'
};
from the documentation for Dual-Y Charts...
In the Material code ..., the axes and series options together specify the dual-Y appearance of the chart. The series option specifies which axis to use for each. The axes option then makes this chart a dual-Y chart.
In the Classic code, this differs slightly. Rather than the axes option, you will use the vAxes option (or hAxes on horizontally oriented charts). Also, instead of using names, you will use the index numbers to coordinate a series with an axis using the targetAxisIndex option.
see following working snippet, which draw both...
google.charts.load('current', {packages:['corechart', 'line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Height');
data.addColumn('number', 'Weight')
data.addRows([
['2016-07-27',51,3.4],
['2016-08-03',52,4],
['2016-08-10',53,5],
['2016-08-17',54,6],
['2016-08-24',55,7],
['2016-08-31',56,8]
]);
var optionsMatl = {
title: 'Height-Weight graph',
width: 900,
height: 500,
series: {
0: {axis: 'Height'},
1: {axis: 'Weight'}
},
axes: {
y: {
Height: {label: 'Height (cm)'},
Weight: {label: 'Weight (kg)'}
}
}
};
var chartMatl = new google.charts.Line(document.getElementById('chart_div_matl'));
chartMatl.draw(data, google.charts.Line.convertOptions(optionsMatl));
var optionsCore = {
title: 'Height-Weight graph',
width: 900,
height: 500,
legend: {
position: 'top',
alignment: 'end'
},
series: {
1: {
targetAxisIndex: 1
}
},
vAxes: {
0: {
title: 'Height (cm)',
},
1: {
title: 'Weight (kg)'
}
},
theme: 'material'
};
var chartCore = new google.visualization.LineChart(document.getElementById('chart_div_core'));
chartCore.draw(data, optionsCore);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>Material Chart</div>
<div id="chart_div_matl"></div>
<div>Core Chart</div>
<div id="chart_div_core"></div>
I want to draw a chart in which x-axis is a date.
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
var data = new google.visualization.DataTable();
data.addColumn('string', 'x');
data.addColumn('number', 'history');
data.addRows([
[{v: 1, f:'11-05-2010'}, 10],
[{v: 2, f:'11-05-2011'}, 20],
[{v: 3, f:'11-05-2012'}, 34],
[{v: 4, f:'11-05-2013'}, 48]
]);
var options = {
title: '<?php echo $strings["updates_task"]; ?>',
legend: 'none',
lineWidth: 2,
hAxis: { minValue: 0, maxValue: 9 },
vAxis: {
minValue: 0,
gridlines: {
color: 'none',
count: 5
}
},
colors: ['#FF0000'],
pointSize: 10,
pointShape: 'square',
width:1200,
height:500
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
When I used x as string then date is showing but not the vertical line.
When I used x as number then vertical lines are shown but 2.5,5,7.5 are shown in place on date. But I want to show both. How can I show both?
I am creating google barchart, that takes data from database.The problem is that data contains values below "1" like 0.6,0.7 etc
It wont appear on graph. Graph only shows values starting from 1.
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: 'string',
role: 'annotation',
sourceColumn: 1,
calc: 'stringify'
}]);
var options = {
width: 395,
height: 200,
title: 'Values',
'chartArea': {right: 37,width:'40%'},
titleTextStyle: {
fontName: 'Arial',
fontSize: 14
},
legend: {position: 'none'},
colors:['#4A9218'],
};
var chart = new google.visualization.BarChart(document.getElementById('ch7'));
chart.draw(view, options);
}
</script>
<div id="ch7" style="width:33%; height:200px"></div>
If your values are all positive you can use logarithmic scale setting option hAxis.logScale to true. Othervise you can set also minimum value to be shown. Options are set like:
hAxis: {
logScale: true
}
or like
hAxis: {
minValue: 0
}