I am pulling data from a database via mysqli to create a Google pie Chart. The data is from one column (a1), but each entry is different (eg, a, b, c) and I am listing the percentage of responses for each entry/answer.
So for instance,
a = 20%
b = 30%
Each entry corresponds to a different social media type, which I need to show but is not shown in the database itself. Is there a way to change the legend of the chart so that instead of listing A, B, C it would replace that with a custom label? (Eg, instead of showing 'A' show 'Facebook').
my column
my current chart
I have tried using title under var data, label under options, legend under options. I feel like I'm missing something
<?php
$connect = mysqli_connect("localhost", "root", "root", "survey");
$query = "SELECT a1, count(*) as number FROM rtp2k GROUP BY a1";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Sad me is Sad </title>
<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([
['social', 'number'],
<?php
while($row = mysqli_fetch_array($result))
{
echo "['".$row["a1"]."', ".$row["number"]."],";
}
?>
]);
var options = {
title: 'Which social networks do you use most often?',
//is3D:true,
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<br /><br />
<div style="width:900px;">
<h3 align="center">Make Simple Pie Chart by Google Chart API with PHP Mysql</h3>
<br />
<div id="piechart" style="width: 900px; height: 500px;">
</div>
</div>
</body>
</html>
Right now my legend lists the type by what is in the database, (eg, a, b, c) I would like to replace the letters with my own label/title (eg, instead of 'a', I would like it to say 'Facebook'.
Edited for consistency.
we can use a DataView with a calculated column,
to convert the values the network names.
first, create an object to map the values to the names.
var socialNetworks = {
a: 'Facebook',
b: 'Instagram',
c: 'LinkedIn'
};
then we create a DataView from the DataTable.
var view = new google.visualization.DataView(data);
then use method setColumns to add a calculated column for the conversion.
we use the column index of the number, since it won't be changing.
view.setColumns([{
calc: function (dt, row) {
return socialNetworks[data.getValue(row, 0)];
},
label: 'social',
type: 'string'
}, 1]);
then use the DataView to draw the chart.
chart.draw(view, options);
full snippet...
var data = google.visualization.arrayToDataTable([
['social', 'number'],
<?php
while($row = mysqli_fetch_array($result))
{
echo "['".$row["a1"]."', ".$row["number"]."],";
}
?>
]);
var options = {
title: 'Which social networks do you use most often?',
//is3D:true,
pieHole: 0.4,
};
var socialNetworks = {
a: 'Facebook',
b: 'Instagram',
c: 'LinkedIn'
};
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function (dt, row) {
return socialNetworks[data.getValue(row, 0)];
},
label: 'social',
type: 'string'
}, 1]);
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(view, options);
Related
I have cretae a column chart using Google chart which display a aggregate value. I've add a listener to enable some action when a column is selected.
The listener works as the alert statement displays the element I'd like to use.
How can I save into a php variable the selected item.
I looking for the code to be added in the pp section at the bottom of the display code below .
<div id="chart_div" style="height:400px;width:450px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["SousCat_Nom", "Valeur", { role: "style" } ],
<?php
while($row4 = mysqli_fetch_array($resultAll))
{
echo "['".$row4["SousCat_Nom"]."', ".$row4['Valeur']." ,'#4d5ae3'],";
}
?>
]);
var options = {
chart: {
title: 'Dépenses par catégories ',
}
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler() {
var selectedItem = chart.getSelection()[0,0];
if (selectedItem) {
var value = data.getValue(selectedItem.row, 0);
alert('The user selected ' + value);
<?php
// $data = ?????? ;
?>
}
}
}
</script>
I've been trying to display a graph in each row inside one page using Google chart but
I have no idea how to do that.
I get data from database when making a graph.
putting aside if this code below is right, here's my image.
#foreach ($titles as $title)
{{$title->title_name}}
<?php $getData = App\Graph::getNumber($title->id)?>
<div id="graph_bar{{$title->id}}" ></div> ←graph
#endforeach
<script type="text/javascript">
var barA= #json($getData->numberA);
var barB = #json($getData->numberB);
var barC= #json($getData->numberC);
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawchart);
function drawchart() {
var data = google.visualization.arrayToDataTable([
['', '', '', ''],
['', barA, barB , barC],
]);
var options = {
isStacked: true,
isStacked:'percent',
legend: {position: 'none'},
series: {
0:{color:'red'},
1:{color:'blue'},
2:{color:'grey'},
}
};
var chart = new google.visualization.BarChart(document.getElementById('graph_bar'));
chart.draw(data, options);
}
$(window).resize(function(){
drawchart();
});
</script>
1.Is it possible to do that(display a graph in each row) in the first place?
2.I'd like to get ID from HTML at javascript.
if anyone knows anything about this, I'd appreciate if if you would help me out.
thank you.
Im new to php and mysql and we have a project where we want to display a specific users input in a google chart.
In the mysql table I have 2 different values (admin, test) under a row called user_name.
When the code is as I linked, the chart shows all the inputs, no matter if they are from the user "test" or the user "admin" and works as it should.
But when I change
$query="
select *
from temp
"
to
$query=
"select *
from temp
where user_name=test
"
the chart stops working.
Any help how to solve this is much appreciated!
<!-- The scripts for the graph -->
<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([
['Day', 'Outdoor', 'Indoor'],
//PHP Code
<?php
$query="select * from temp";
$res=mysqli_query($mysqli,$query);
while($data=mysqli_fetch_array($res)){
$day=$data['created_at'];
$outdoor=$data['outdoor'];
$indoor=$data['indoor'];
?>
['<?php echo $day;?>',<?php echo $outdoor;?>,
<?php echo $indoor;?>],
<?php
}
?>
]);
var options = {
title: 'Temperature',
subtitle: 'Temperature outside and inside',
curveType: 'none',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart
(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
mysql table:
i am using google chart and displaying column chart. That's working fine. my code is
google.charts.load('current', {'packages':['columnchart']});
google.charts.setOnLoadCallback(drawChartTwo);
function drawChartTwo() {
var data = google.visualization.arrayToDataTable([
['Type', 'Total'],
<?php
foreach($val as $data){
echo "['".$data['type']."', ".$data['total']."],";
}
?>
]);
var options = {
hAxis: {
title: 'Type'
},
vAxis: {
title: 'Total'
},
'width':830,
'height':300,
'title': 'Outage Analysis',
'is3D': true,
//set color base on $data['unit']
};
var chart1 = new google.visualization.ColumnChart(document.getElementById('chart_bar'));
chart1.draw(data, options);
}
now, in my database i have another column $data['unit'] and it have four different category and i want to display different colors of column for different category. so, my question is how can i use my php column $data['unit'] to set colors on column in column chart?
use a 'style' column role
you can populate the column with html color strings...
e.g. --> #f44336
var data = google.visualization.arrayToDataTable([
['Type', 'Total', {role: 'style'}],
<?php
foreach($val as $data){
echo "['".$data['type']."', ".$data['total'].", '".$data['color']."'],";
}
?>
]);
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var data = new google.visualization.arrayToDataTable([
['Type', 'Total', {role: 'style'}],
['A', 10, '#f44336'],
['B', 14, '#e91e63'],
['C', 16, '#9c27b0'],
['D', 22, '#673ab7'],
['E', 28, '#3f51b5'],
['F', 14, '#2196f3']
]);
var options = {
height: 300,
legend: {
position: 'none'
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(container);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I need some help. I have some info in my db that I want to show in 2 charts using Google charts script.
Both scripts works but not when I use both scripts in a same page.. I bet is a problem with the while that are both equals since I need to show the same info. If I delete the first while the second loop start to work, but if no, the first just work.
The app works well because if I hardcode the values by hand and without the while works well both..
Here's the code:
<!-- First Chart start here: -->
<script type="text/javascript">
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Formato', 'Cantidad'], <? php
//da problema si hay 2 while
while ($DatRDV = mysql_fetch_array($nrollos)) {
echo "['".$DatRDV['Formato'].
"',".$DatRDV['nRollos'].
"],";
} ?> ]);
var options = {
title: 'Formato de Rollos'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<!-- Second chart start here: -->
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var JSONObject = {
cols: [{
id: 'format',
label: 'Formato',
type: 'string'
}, {
id: 'cantidad',
label: 'Cantidades',
type: 'number'
}],
rows: [
<? php
while ($DatRDV = mysql_fetch_array($nrollos)) {
echo "{c:[{v: '".$DatRDV['Formato'].
"'}, {v: ".$DatRDV['nRollos'].
"}]},";
} ?> ]
};
var data = new google.visualization.DataTable(JSONObject, 0.5);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {
'allowHtml': true
});
}
google.setOnLoadCallback(drawVisualization);
</script>
try;
mysql_data_seek($nrollos,0);
before the 2nd loop