I have a multi-chart Google Visualization script (1 column chart and 2 line charts). The charts are working/displaying correctly except for the var Options code. The most important part of the Options section is being able to change the column/line color. So I tried changing it using the role: 'style'} alternative, but it didn't work either.
Please see below code for the 3 charts. I'm new to Google Visualization, so any feedback/help is much appreciated!
google.charts.load('current', {
packages: ['corechart', 'controls']
}).then(function () {
// Chart data
var data = [];
data[0] = google.visualization.arrayToDataTable ([["Date","Sessions", {role: 'style'}],
<?php
for($a = 0; $a < 7; $a++)
{
echo "['".$date[$a]."', ".$sessions[$a].", 'fill-color: #76A7FA'],";
}
?>
]);
data[1] = google.visualization.arrayToDataTable ([["Date","Sessions"],
<?php
for($a = 0; $a < 31; $a++)
{
echo "['".$date[$a]."', ".$sessions[$a]."],";
}
?>
]);
data[2] = google.visualization.arrayToDataTable ([["Date","Sessions"],
<?php
for($a = 0; $a < count($query); $a++)
{
echo "['".$date[$a]."', ".$sessions[$a]."],";
}
?>
]);
var current = 0;
var current_chart = 0;
// Create and draw the visualization
var chart = [];
chart[0] = new google.visualization.ColumnChart(document.getElementById('sessions_chart'));
chart[1] = new google.visualization.LineChart(document.getElementById('sessions_chart'));
function drawChart() {
// Disabling the buttons while the chart is drawing.
document.getElementById('week_btn').disabled = true;
document.getElementById('month_btn').disabled = true;
document.getElementById('all_btn').disabled = true;
google.visualization.events.addListener(chart, 'ready', function() {
// Enable the buttons after the chart has been drawn
document.getElementById('week_btn').disabled = false;
document.getElementById('month_btn').disabled = false;
document.getElementById('all_btn').disabled = false;
});
var view = new google.visualization.DataView(data[current]);
var options = {
title: 'Number of Sessions',
vAxis: {title: "# of Sessions", minValue:0},
hAxis: {format: 'MMM d, y'},
colors: 'lightgreen'
};
// Convert first column to date format
view.setColumns([{
calc: function (dt, row) {
return new Date(dt.getValue(row, 0));
},
label: data[current].getColumnLabel(0),
type: 'date'
}, 1]);
chart[current_chart].draw(view, data[current], options);
}
drawChart();
// google.charts.setOnLoadCallback(drawChart);
document.getElementById('week_btn').addEventListener("click", displayWeek);
function displayWeek() {
current = 0;
current_chart = 0;
drawChart();
}
document.getElementById('month_btn').addEventListener("click", displayMonth);
function displayMonth() {
current = 1;
current_chart = 1;
drawChart();
}
document.getElementById('all_btn').addEventListener("click", displayAll);
function displayAll() {
current = 2;
current_chart = 1;
drawChart();
}
});
the colors option should be an array...
colors: ['lightgreen']
as for the style role, try providing only the color...
echo "['".$date[$a]."', ".$sessions[$a].", '#76A7FA'],";
AND
highly recommend NOT building json manually in php from a string.
instead, separate the php from the html in two different files.
build the data in php and return the encoded json to the page.
then use ajax to call the php page and get the encoded json.
then draw the chart.
here are some examples...
How to automatically update Google Gauge
JSON $ajax problems
Related
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 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);
In Google chart- when i call the function to remove comma from variable from input , it wont work.
What i want is result from ldsalary(without comma) update in Google chart. ldsalary value is calculated and shown while onkeyup. It will be changing.
update : made a jsfiddle
onkeyup:
document.getElementById('cal').onkeyup=function(){
calculator();
drawChart();
reformat function:
function reformat(str) {
while (str.search(",") >= 0) {
str = (str + "").replace(',', '');
}
return str;
};
Calculator function, this updates ldsalary with new value:
function calculator(){
.........
var jldsalary = document.getElementById("ldsalary");
xm = a * Math.pow(1 + jasincrease / 100, b);
jldsalary.value = rounding(xm).toLocaleString();
}
Chart:
<script type="text/javascript">
var rage = 55 ;
var slry = 5000;
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
rage =document.getElementById('rage').value *1;
var xxx = document.getElementById('ldsalary').value *1;
// if i add this google chart wont show.
slry.value =reformat(xxx); // without reformat, there will be ',' value.
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Amount');
data.addRows([
[0, 0], [rage,slry],
[100, 0]
]);
var options = {
curveType: 'function',
width: 500,
height: 200,
hAxis: {
title: 'Age'
},
vAxis: {
title: 'Amount'
}
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
Its been a day doing all kinds of solutions. Advance thanks for helping me.
as per your code, you have defined slry as a variable, and trying to use spry.value, which is not valid at all, change:
...
slry.value =reformat(xxx); //its just a variable not input element
to
...
slry = reformat(xxx);
The problem was in reformat().
function reformat(str) {
return parseInt(str.replace(',', ''));
}
Now it works: as value in input box changes , google graph too changes.
I tried to create line chart using google chart apis and other for following csv data. None of them helped:
csv data looks like this:
"Date,Term,Segment,Visitor"
"2014/01/01,2014/01/01 - 2014/01/31,All visitors,2"
"2014/01/01,2014/01/01 - 2014/01/31,New user,0"
"2014/01/01,2014/01/01 - 2014/01/31,Mobile traffic,0"
"2014/01/02,2014/01/01 - 2014/01/31,All visitors,7"
"2014/01/02,2014/01/01 - 2014/01/31,New user,1"
"2014/01/02,2014/01/01 - 2014/01/31,Mobile traffic,0"
"2014/01/03,2014/01/01 - 2014/01/31,All visitors,5"
"2014/01/03,2014/01/01 - 2014/01/31,New user,0"
"2014/01/03,2014/01/01 - 2014/01/31,Mobile traffic,0"
"2014/01/04,2014/01/01 - 2014/01/31,All visitors,3"
.............
I faced many issue while using google chart as you can find here:
CSV data loading give Not enough columns given to draw the requested chart
Is it possible to create line chart for this short of data?
Chart should look like this:
--------UPDATED CODE -----------
Why does it not show EVEN dates on X- axix?
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="http://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get("Chart3-data1.csv", function(csvString) {
var transData = [['Date', 'All visitors', 'New user', 'Mobile traffic']];
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
for (var i = 1; i < arrayData.length; i++) {
console.log(arrayData[i][0]);
var fields = arrayData[i][0].split(',');
console.log(fields);
switch ( (i - 1) % 3) {
case 0:
var allVisitors = parseInt(fields[3]);
break;
case 1:
var newUser = parseInt(fields[3]);
break;
case 2:
var mobile = parseInt(fields[3]);
transData.push([ fields[0], allVisitors, newUser, mobile] );
break;
}
}
var data = new google.visualization.arrayToDataTable(transData);
var options =
{
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('gauge'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<div id="gauge" style="width: 900px; height: 500px;"></div>
</body>
</html>
Resulting graph:
I'd change your csv data to:
Date, All visitors, New user, Mobile traffic
2014/01/01, 2, 0, 0
2014/01/02, 7, 1, 0
2014/01/03, 5, 0, 0
2014/01/04, 3, 0, 2
2014/01/05, 4, 1, 2
From those data this chart is produced (no changes in code):
Change of data - one option with JS:
$.get("chart-data-orig.csv", function(csvString) {
var transData = [['Date', 'All visitors', 'New user', 'Mobile traffic']];
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// index 0 is header which will be changed
for (var i = 1; i < arrayData.length; i++) {
console.log(arrayData[i][0]);
var fields = arrayData[i][0].split(',');
console.log(fields);
switch ( (i - 1) % 3) {
case 0:
var allVisitors = parseInt(fields[3]);
break;
case 1:
var newUser = parseInt(fields[3]);
break;
case 2:
var mobile = parseInt(fields[3]);
transData.push([ fields[0], allVisitors, newUser, mobile] );
break;
}
}
var data = new google.visualization.arrayToDataTable(transData);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
});
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.