How do I display PHP array in Google Chart - javascript

I'd like to diplay my array in google stacked column chart. I generated the array looks like this.
array(n) { ["5pm"]=> int(4) ["6pm"]=> int(0),... } //Monday
array(n) { ["5pm"]=> int(5) ["6pm"]=> int(1),... } //Tuesday
...
array(n) { ["5pm"]=> int(4) ["6pm"]=> int(2),... } //Sunday
The number of entries in array needs to vary (depends on entries in database, but is the same for all days).
The JS from google charts needs to look like this
var data = google.visualization.arrayToDataTable([
['Hours', '5pm', '6pm',...],
['Mon', 4, 0],
['Tue', 5, 1],
...
['Sun', 4, 2]
]);
Thanks for the help ;)

Heer is a sample code where I'm getting data from PHP & passing that to JavaScript for plotting the chart. One thing needs to check that all rows should have an equal number of elements.
So, according to your question, all "Time Periods" rows should have an equal number of elements else, it'll not work.
<?php
$chartData = array(
array('Year', 'Sales', 'Expenses', 'Profit'),
array('2014', 1000, 400, 200),
array('2015', 1170, 460, 250),
array('2016', 660, 1120, 300),
array('2017', 1030, 540, 350)
);
$chartDataInJson = json_encode($chartData);
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $chartDataInJson; ?>);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
</head>
<body>
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
</body>
</html>
Hope it'll clear all of your doubt.

Related

How to implement my own data in google charts?

I have the following pandas dataframe that has the columns X and Y (a total of 50 rows)
x y
0 -5.000000 -172.000000
1 -4.816471 -155.131174
2 -4.632942 -139.370476
3 -4.449413 -124.680815
And I want to implement it in a google chart
I copied the code from google:
<html>
<head>
<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([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>
but I did not find any way to insert the dataframe values into the chart (other than inserting them manually)
I tried converting the dataframe into csv, json, text, sqlite_db, I even tried inserting the data using flask and ninja, but all of those did not seem to work.

Prevent Google Charts from escaping apostrophes in a title of a chart

I'm using google Bar Charts https://developers.google.com/chart/interactive/docs/gallery/barchart. The titles for are stored in a database and some them contain apostrophes. Those apostrophes in the title are rendered as &39, for example "he's" ---> "he&39s"
I want apostrophes to be rendered normally.
I've found several solutions but none of them worked so far for such a simple task.
Any working solution?
update:
This is rendered properly, as I'm goooood
var chart = new google.visualization.ColumnChart(document.getElementById("my_div"));
chart.draw(data, {
title: "I'm goooood",
legend: {position: "none"},
});
But this - not, it's ---> I'm goooood
var chart = new google.visualization.ColumnChart(document.getElementById("my_div"));
chart.draw(data, {
title: "<%= get_value_from_db() %>",
legend: {position: "none"},
});"
On other pages, without charts but text only, the "<%= get_value_from_db() %>" gets rendered correctly -- I'm goooood.
I've had the same issue but only with ' and " which get rendered as "&39," or "&34," .
As none of the above fixes worked for me, a quick and pretty dirty solution I've relied upon is using string.replace with the prime ( ′ ), and double prime ( ″ ) symbols - looped through a reasonable number of times.
<%= varName.replace("\'",'′').replace("\"",'″ ') %>
Also I think this error may have something to do with how Google Charts and EJS interact together as both the OP and I are using it and have this issue. (pure speculation)
Use \ to escape '. Look at the example
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
var options = {
chart: {
title: 'Company\'Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
},
bars: 'horizontal' // Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
</head>
<body>
<div id="barchart_material" style="width: 900px; height: 500px;"></div>
</body>
</html>
As you are getting tittle from db, you have to add \ before ' in title string using string manipulation.
you can use a dom element to convert the ascii characters to readable text
function convertToText(ascii) {
var tempDiv = document.createElement('DIV');
tempDiv.innerHTML = ascii;
return tempDiv.textContent || tempDiv.innerText || '';
}
in your options...
chart.draw(data, {
title: convertToText("<%= get_value_from_db() %>"),
legend: {position: "none"},
});
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['x', 'y'],
['A', 9],
['B', 30],
['C', 50],
['D', 70],
['E', 90]
]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {
title: convertToText('I'm goooood'),
legend: {position: 'none'},
});
function convertToText(ascii) {
var tempDiv = document.createElement('DIV');
tempDiv.innerHTML = ascii;
return tempDiv.textContent || tempDiv.innerText || '';
}
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Just use decodeURI on the text.
My title comes from what the user has chosen from categories.
So, when I show the chart title, I do like this:
title: decodeURI(strCategory) + ' from ' + decodeURI(strInitialDate) + ' to ' + decodeURI(strEndDate)
My categories include, 'Alimentação', 'Feira/Sacolão' and others...
It works even on smartphones.
Added: Works with alerts also...
alert('Sem dados para o período de: ' + decodeURI(strInitialDate) + ' a ' + decodeURI(strEndDate))

Google Charts API: more than one label rows on x axis?

I have this chart which is a bar chart showing multiple data. The data is divided by year (2014, 2015) and quarter (Q1,Q2,Q3,Q4). I can show either the quarters on the x-axis or the year, but not both. I made a screenshot and put the years in there to show what I'd like to achieve.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<body>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['bar']});
google.setOnLoadCallback(drawBasic);
function drawBasic() {
//create data table object
var data = google.visualization.arrayToDataTable([
['','Sales', 'Expenses'],
['Q1',1000, 400],
['Q2',1000, 400],
['Q3',1170, 460],
['Q4',900, 500],
['Q1',1400, 420],
['Q2',1240, 750],
['Q3',1001, 360],
['Q4',788, 800]
]);
var options = {
width: 800, height: 600, is3D: false, title: 'Company Earnings'
};
var chart = new google.charts.Bar(
document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
<div id="chart_div"></div>
</body>
</html>
Here is the result (I added the years in paint):
Any ideas how to do this?
I remembered seeing the following post sometime back that lets you add multiple x-axis details. Perhaps this will help:
http://www.lornajane.net/posts/2011/adding-multiple-axis-labels-to-a-google-chart

How to plot all values in google column chart?

I'm trying to plot a Google column chart from the data where there is a huge range between the highest values and the lowest values.The chart is plotting correctly for the large values but when the values are too small it is not plotting any column for that values.I want to plot all values no matter it is 0.02 or 5000 .If i use the option logScale:true then it plots all the values but the chart starts from 1 and the values less than 1 goes to negative Y Axis. How to solve this problem without increasing the height of the chart so that it starts from 0 point and plots all the values including negative values? I also tried to set
viewWindow: {
max:100
min:0
}
but did not work!
Here is my code
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'profit'],
['2004', 1000, 4],
['2005', 0.1, -460],
['2006', 660, 2],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}},
vAxis:{logScale:true ,
viewWindowMode:'explicit',
viewWindow: {
max:100,
min:0
}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>

chart title from <input type='text'> with jquery

I'm new with jquery.
I have a html and jquery that plots a line chart from a csv. I would like to write a text in a textbox and append it to my chart.
Any help is appreciated :)
<div class="optionGroup"><label for="chart_title">Title</label><input type="text" name="chart_title" value="" id="chart_title"></div>
var chart = new google.visualization.LineChart(document.getElementById('chart'));
//this is my attempt
var titlus = +$('#chart_title').keyup(function(){
var value = $( this ).val();
$( 'chart' ).text( value );
})
var options = {
title: titlus,//<--it should go here
hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
legend: 'none'
};
chart.draw(view, options);
You need to render the graph in the beginning, if you want to change the graph title in real time you should draw the graph again when a key is pressed. In order to do this a callback function for load must be added because the rendering/API is asynchronous. As a recommendation, it is a not a good practice rendering the graph any time a key is pressed, it is better to create a button to submit the title or detecting when the return key is pressed. This is a working example of what you asked:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
document.getElementById("chart_title").onkeyup = function() {
options.title = this.value;
chart.draw(data, options);
}
}
</script>
</head>
<body>
<div>
Title: <input type="text" name="chart_title" value="" id="chart_title">
</div>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>

Categories

Resources