I am displaying a chart using Google API and I am getting a chart but it is not displaying that line in the graph,
This is the code I am trying with, I am using array data for charts,
var jsonlength = data.feed.entry.length;
var timestamp = new Array(jsonlength);
var temperature = new Array(jsonlength);
var tempid = new Array(jsonlength);
for (var i = 0; i < jsonlength; i++) {
timestamp[i] = ((data.feed.entry[i].gsx$timestamp.$t));
temperature[i] = ((data.feed.entry[i].gsx$temperaturevalue.$t));
}
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data1.addColumn('number', 'X');
data1.addColumn('number', 'X');
for (var i = 0; i < jsonlength; i++) {
console.log(i);
data1.addRows(i,data.feed.entry[i].gsx$temperaturevalue.$t);
//Here I can display all those values, But still not getting the chart, Though I have given proper values, Help me here
console.log(data.feed.entry[i].gsx$temperaturevalue.$t);
}
var options = {
hAxis: {
title: 'Date'
},
vAxis: {
title: 'Temperature'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data1, options);
This is the output I am getting without a line, Please help me I am new to this
Output without a line in the graph
most likely is due to 'string' values vs. number
try this...
temperature[i] = (parseFloat(data.feed.entry[i].gsx$temperaturevalue.$t));
here...
for (var i = 0; i < jsonlength; i++) {
timestamp[i] = ((data.feed.entry[i].gsx$timestamp.$t));
temperature[i] = (parseFloat(data.feed.entry[i].gsx$temperaturevalue.$t));
}
EDIT
here, you create data
var data = new google.visualization.DataTable();
but then you're adding columns to data1 ???
data1.addColumn('number', 'X');
data1.addColumn('number', 'X');
try syncing up the variable names and check addRow below...
var data1 = new google.visualization.DataTable();
data1.addColumn('number', 'X');
data1.addColumn('number', 'X');
for (var i = 0; i < jsonlength; i++) {
// use addRow -- which takes an array
data1.addRow([i,data.feed.entry[i].gsx$temperaturevalue.$t]);
}
var options = {
hAxis: {
title: 'Date'
},
vAxis: {
title: 'Temperature'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data1, options);
Related
I have the following code to create the chart.
PHP:
SELECT A.Mes, A.Total, A.Categoria
FROM
(SELECT raddb.Categorias.Categoria, DATE_FORMAT(Reportado, '%Y-%m') AS Mes, COUNT(raddb.Denuncias.Categoria) AS Total
FROM raddb.Categorias LEFT OUTER JOIN raddb.Denuncias ON raddb.Denuncias.Categoria = raddb.Categorias.id
GROUP BY DATE_FORMAT(Reportado, '%Y-%m'), raddb.Categorias.Categoria) AS A WHERE A.Total > '0'");
$stmt->execute();
$json = [];
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$json[]= [(string)$Mes, (int)$Total, (string)$Categoria];
}
echo json_encode($json);
Data returned from php:
Mes, Total, Categoria
2022-05, 1, Bullying (Mobbing, Bossing, Pessoal, Gossip)
2022-05, 1, Preocupação relativas à saúde e segurança
2022-05, 2, Suspeita de Roubo, Corrupção ou Desfalque
2022-05, 1, Feedback positivo ou elogio
Then the html and javascript:
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart1);
function drawChart1() {
$.getJSON('denunciasmes.php', function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('string', '');
tdata.addColumn('number', 'Total');
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i][0], parseInt(data[i][1]) ]);
}
var options = {
chart: {
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(tdata, google.charts.Bar.convertOptions(options));
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="columnchart_material" style="height: 500px;"></div>
Now the problem is that the graph only returns the month and the total of each category as shown here in the image
But I wanted the category to appear instead of Total. Only then does the graph make sense, because that way it identifies the month, the total for each month and the category it refers to.
Can you help?
I've tried a few ways and I can't. This way it doesn't loop:
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart1);
function drawChart1() {
$.getJSON('denunciasmes.php', function (data) {
for (var i = 0; i < data.length; i++) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('string', '');
tdata.addColumn('number', data[i][2]);
tdata.addRow([data[i][0], parseInt(data[i][1]) ]);
}
var options = {
chart: {
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(tdata, google.charts.Bar.convertOptions(options));
});
}
I've also tried this way:
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart1);
function drawChart1() {
$.getJSON('denunciasmes.php', function (data) {
for (var i = 0; i < data.length; i++) {
teste = data[i][0];
teste1 = data[i][1];
teste2 = data[i][2];
var tdata = new google.visualization.DataTable();
tdata.addColumn('string', '');
tdata.addColumn('number', teste2);
}
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i][0], parseInt(data[i][1]) ]);
}
var options = {
chart: {
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(tdata, google.charts.Bar.convertOptions(options));
});
}
But it returns the same category on all bars created in the chart.
The problem is that I should put the code in js to create the columns according to the data returned from the database, but I'm not able to.
You have to add a third column and then provide the data for it.
tdata.addColumn('string', '');
tdata.addColumn('number', 'Total');
tdata.addColumn('string', 'Category'); // add category column
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i][0], parseInt(data[i][1]), data[i][2] ]); //add category info
}
I am trying to convert a JSON string into an integer so that I can use this data in a google chart. As of right now I can only get one set of data to be displayed in my chart.
Here is my JQUERY code:
$("#shotsandbigcc").click(function(){
//alert("Button works");
$("#shotsandbigcc_popup").toggle();
var integer = $("#shotsandbigcc").attr("name");
//alert("integer: " + integer);
$.ajax('includes/test.php', {
type: 'POST', // http method
data: {myData: integer},// data to submit
dataType: 'json',
success: function(response){
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMultSeries);
function drawMultSeries() {
var len = response.length;
for(var i=0; i<len; i++){
var year = response[i].Year;
var ontarget = parseInt(response[i].Shots_on_Target);
var offtarget = parseInt(response[i].Shots_off_Target);
alert(ontarget);
}
alert(year);
var data = google.visualization.arrayToDataTable([
['Year', 'Shots on Target', 'Shots off Target'],
[year, ontarget, offtarget],
[year, ontarget, offtarget]
]);
var options = {
title: 'Shooting Accuracy',
chartArea: {width: '50%'},
hAxis: {
title: 'Amount of Shots',
minValue: 0
},
vAxis: {
title: 'Year'
}
};
var chart = new google.visualization.BarChart(document.getElementById('shotsandbigcc_chart'));
chart.draw(data, options);
}
}
});
});
The JSON data is in an array which has this format [{"Year":"2019/2020","Shots_on_Target":"302","Shots_off_Target":"578","Accuracy":"0.34"},{"Year":"2020/2021","Shots_on_Target":"74","Shots_off_Target":"93","Accuracy":"0.44"}]
If someone could tell me how I can display both 2019/2020 and 2020/2021 data to be displayed. I would be most grateful as right now only the 2020/2021 data is being displayed. Thank you.
For integet value part:
var ontarget = parseInt(response[i].Shots_on_Target);
For your data part:
var vizData = [];
vizData.push(['Year', 'Shots on Target', 'Shots off Target']);
for(var i=0; i<len; i++){
var year = response[i].Year;
var ontarget = parseInt(response[i].Shots_on_Target);
var offtarget = parseInt(response[i].Shots_off_Target);
vizData.push([year, ontarget, offtarget]);
alert(ontarget);
}
alert(year);
var data = google.visualization.arrayToDataTable(vizData);
explaination: since in the loop the values are getting updated in every iteration so, the 'year', 'ontarget' and 'offtarget' will have the latest values only. So on every iteration you have to store values so that they do not get overwritten. For that now this code is pushing in array in every iteration preserving the previous values. Which now you can use in the google.visualization function.
Happy Coding!
I'm trying to draw ComboChart. My problem is that chart keep adding dates in between values, which makes chart unnecessary big:
My code:
var chart;
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var graphData = [{"date":new Date(1470903103000),"count1":47,"count2":3},
{"date":new Date(1472134276000),"count1":92,"count2":20},
{"date":new Date(1472198154000),"count1":92,"count2":15}];
rowCount = graphData !== undefined ? graphData.length : 0;
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Count1');
data.addColumn("number", "Count2");
for (var i = 0; i < rowCount; i++) {
var gDate = graphData[i].date;
var gCount1 = graphData[i].count1;
var gCount2 = graphData[i].count2;
data.addRow([ gDate, gCount1, gCount2]);
}
var options = {
title : 'Overview',
vAxis: {title: 'Count'},
hAxis: {title: 'Date'},
seriesType: 'bars',
series: { 1: { type: 'line' } },
//chartArea: { left: 0, top: 0, width: "80%", height: "80%" },
height: 200,
width: 500
};
chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
or go to fiddle
Solution is pretty simple, I simply had to send string instead of dateTime:
data.addColumn('datetime', 'Date'); => data.addColumn('string', 'Date'); and var gDate = graphData[i].date; => var gDate = graphData[i].date.toString();
I'm trying to draw two charts using the Google Charts API. I set up my HTML like this:
<div id="page_views" data-title="{{ report['page_views']['title'] }}" data-labels="{{ report['page_views']['labels'] }}" data-rows="{{ report['page_views']['rows'] }}"></div>
<div id="event_views" data-title="{{ report['event_views']['title'] }}" data-labels="{{ report['event_views']['labels'] }}" data-rows="{{ report['event_views']['rows'] }}"></div>
where the data attributes are filled during template rendering. I then use the following javascript to attempt to draw my charts:
google.load('visualization', '1.0', {packages: ['line']});
google.setOnLoadCallback(drawCharts);
function drawPageViews() {
var data = new google.visualization.DataTable();
var page_views = document.getElementById("page_views");
var labels = eval(page_views.dataset.labels);
data.addColumn('number', "Day");
for(var i = 0; i < labels.length; i++) {
data.addColumn('number', labels[i]);
}
var rows = eval(page_views.dataset.rows);
data.addRows(rows);
var options = {
chart: {
title: page_views.dataset.title
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('page_views'));
chart.draw(data, options);
}
function drawEventViews() {
var data = new google.visualization.DataTable();
var event_views = document.getElementById("event_views");
var labels = eval(event_views.dataset.labels);
data.addColumn('number', "Day");
for(var i = 0; i < labels.length; i++) {
data.addColumn('number', labels[i]);
}
var rows = eval(event_views.dataset.rows);
data.addRows(rows);
var options = {
chart: {
title: event_views.dataset.title
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('event_views'));
chart.draw(data, options);
}
function drawCharts() {
drawPageViews();
drawEventViews();
}
The result that I get is that one of the charts is drawn while the other contains an SVG with an empty tag and nothing else inside. Which chart gets drawn is random. Commenting out either draw function makes the other single chart draw as expected.
It seems like there must be some sort of shared global state or variable but it looks to me like everything is defined in the different draw functions. When I look up similar questions people offer solutions which look very much like what I'm doing. What am I missing?
It seems this behavior is related with draw function, in particular it occurs once multiple charts is rendered on the page.
According to the documentation:
The draw() method is asynchronous: that is, it returns immediately,
but the instance that it returns might not be immediately available.
For rendering multiple charts on the page you could consider the following approach: render the next chart once the previous one is rendered, this is where ready event comes to the rescue.
Having said that the solution would be to replace:
function drawCharts() {
drawPageViews();
drawEventViews();
}
with
function drawCharts() {
drawPageViews(function(){
drawEventViews();
});
}
where
function drawPageViews(chartReady) {
//...
var chart = new google.charts.Line(document.getElementById('page_views'));
if (typeof chartReady !== 'undefined') google.visualization.events.addOneTimeListener(chart, 'ready', chartReady);
chart.draw(data, options);
}
and
function drawEventViews(chartReady) {
//...
var chart = new google.charts.Line(document.getElementById('event_views'));
if (typeof chartReady !== 'undefined') google.visualization.events.addOneTimeListener(chart, 'ready', chartReady);
chart.draw(data, options);
}
Working example
google.load('visualization', '1.0', { packages: ['line'] });
google.setOnLoadCallback(drawCharts);
function drawPageViews(chartReady) {
var data = new google.visualization.DataTable();
var page_views = document.getElementById("page_views");
var labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
data.addColumn('string', 'Day');
data.addColumn('number', 'PageViews');
var rows = new Array();
for (var i = 0; i < labels.length; i++) {
rows.push([labels[i], getRandomInt(0, 100)]);
}
data.addRows(rows);
var options = {
chart: {
title: 'Page views'
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('page_views'));
if(typeof chartReady !== 'undefined') google.visualization.events.addOneTimeListener(chart, 'ready', chartReady);
chart.draw(data, options);
}
function drawEventViews(chartReady) {
var data = new google.visualization.DataTable();
var event_views = document.getElementById("event_views");
var labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
data.addColumn('string', 'Day');
data.addColumn('number', 'EventViews');
var rows = new Array();
for (var i = 0; i < labels.length; i++) {
rows.push([labels[i], getRandomInt(0, 100)]);
}
data.addRows(rows);
var options = {
chart: {
title: 'Event views'
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('event_views'));
if(typeof chartReady !== 'undefined') google.visualization.events.addOneTimeListener(chart, 'ready', chartReady);
chart.draw(data, options);
}
function drawCharts() {
drawPageViews(function(){
drawEventViews();
});
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="page_views"></div>
<div id="event_views"></div>
I am trying to display data using Google's Column chart. I tried displaying bars not stacked but it would not display one bar from both ends. Then i changed the property isStacked to true, it displays all the bars but it crops the bar at the both ends.
How can i fix this issue?
I was playing around with the options but nothing seems to work.
<script type='text/javascript'>
google.load('visualization', '1', { 'packages': ['corechart'] });
google.setOnLoadCallback(drawSizeChart);
var d = 0;
function drawSizeChart() {
$.post('/metrics/SiteResourceChart', { fnsId: "#Model.FnsId", regionId: selectedValue },
function (data) {
if (Object.keys(data).length !== 0) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('date', 'Date');
for (var p = 0; p < data.length; ++p) {
tdata.addColumn('number', data[p][0].PathName);
}
d = data[0].length;
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
var date = new Date(parseInt(data[i][j].CreatedAt.substr(6)));
var rCount = data[i][j].ResourceCount;
if (i === 0)
tdata.addRow([date, rCount, null]);
else
tdata.addRow([date, null, rCount]);
}
}
var options = {
title: 'Resource Count',
titleTextStyle: { fontSize: 20 },
isStacked: true,
bar: { groupWidth: '20%' },
chartArea: { left: '50' },
hAxis: { viewWindowMode: 'maximized' }
//legend: { position: 'none' }
};
var chart = new google.visualization.ColumnChart(document.getElementById('site_size_chart'));
chart.draw(tdata, options);
}
}
);
}
</script>
I guess a quick solution would be to define your first column as 'string' instead of Date and leave the hAxis.viewWindowMode as default. Otherwise, you should configure hAxis.viewWindow object (i.e., min/max values).
Same issue here. What I did is that I added dummy data with a 0 value one day before the first date and one day after the last date in order to achieve the desired result.
Using the columnchart package wasn't a solution for me because I had days without data but wanted to keep the time axis proportional.