Googol charts: how to use getcharttype() - javascript

Thank you for your answer... I'm ALMOST there :) I declared wrapper as global var, I used the getChartType method but still I'm not getting what I need.
so I have these 2 functions now:
var wrapper
function loadEditor() {
// Create the chart to edit.
var table = new google.visualization.Table(document.getElementById('table_div'));
if (sorttest == 1) {
var data = new google.visualization.DataTable(<?=$jsonTableA01?>)
} else {
var data = new google.visualization.DataTable(<?=$jsonTableB01?>)
}
wrapper = new google.visualization.ChartWrapper({
dataTable: data,
left:1,
options: {
'chartArea': {width: '60%', left: 45},
'legend' :'none',
'title':'Number of Newly Opened Roles per <?echo $_SESSION['Display']?>'
}
});
chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', redrawChart);
chartEditor.openDialog(wrapper, {});
}
function sortABC() {
var table = new google.visualization.Table(document.getElementById('table_div'));
var CurrChartType = wrapper.getChartType();
sorttest = 1;
var data = new google.visualization.DataTable(<?=$jsonTableA01?>);
var wrapper = new google.visualization.ChartWrapper({
'chartType': CurrChartType,
dataTable: data,
left:1,
options: {
'chartArea': {width: '60%', left: 45},
'legend' :'none',
'title':'Number of Newly Opened Roles per <?echo $_SESSION['Display']?>'
}
});
I get an error on the 2nd line of sortABC()
var CurrChartType = wrapper.getChartType();
but have no idea why...
please help Bro.. :)

You could determine the chart type using google.visualization.ChartWrapper.getChartType method. In your case you could declare wrapper as global variable (it will be initialized once google.visualization.ChartWrapper is created) to make it accessible in sortABC function. Then you could get current chart type.
The following example demonstrates how to get/set chart type of Google Chart.
Complete example
google.load('visualization', '1.0', { packages: ['charteditor'] });
google.setOnLoadCallback(loadEditor);
var chartEditor = null;
var wrapper = null;
function loadEditor() {
// Create the chart to edit.
wrapper = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'dataSourceUrl': 'http://spreadsheets.google.com/tq?key=pCQbetd-CptGXxxQIG7VFIQ&pub=1',
'query': 'SELECT A,D WHERE D > 100 ORDER BY D',
'options': { 'title': 'Population Density (people/km^2)', 'legend': 'none' }
});
chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', redrawChart);
chartEditor.openDialog(wrapper, {});
}
// On "OK" save the chart to a <div> on the page.
function redrawChart() {
chartEditor.getChartWrapper().draw(document.getElementById('vis_div'));
initChartPanel();
}
function initChartPanel() {
document.getElementById('chartpanel_div').style.visibility = 'visible';
var chartTypes = chartEditor.getChartTypes();
var select = document.getElementById('charttypes_select');
for (var i = 0; i < chartTypes.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = chartTypes[i];
opt.value = chartTypes[i];
select.appendChild(opt);
}
document.getElementById('chart_info').innerHTML = wrapper.getChartType();
}
function changeChartType(sel) {
var chartType = sel.value;
wrapper.setChartType(chartType);
wrapper.draw(document.getElementById('vis_div'));
document.getElementById('chart_info').innerHTML = wrapper.getChartType();
}
#chart_info {
font-weight: bold;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div class="chart_panel" id="chartpanel_div" style=" visibility: hidden" >
<select id="charttypes_select" onchange="changeChartType(this)"></select>
Current Chart Type:<span id="chart_info"></span>
</div>
<div id="vis_div" style="height: 400px; width: 600px;"></div>

Related

Google Visualization Multiple Charts - Options Not Working

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

Unable to display actual chart using Google API in Javascript

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);

How can I draw two material charts with the Google Charts API without one being empty?

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>

setting google chart multiple axes from dynamically generated data

I'm trying to replicate the following code from a working example:
series: {0: {targetAxisIndex:0},
1: {targetAxisIndex:0},
2: {targetAxisIndex:1},
This is for setting which y-axis is used to plot different columns from a dataTable on a Google chart.
However I have a variable number of columns (based on user input), therefore am collecting an array of the required axis (the axisAssignment Array in the below example).
My code is below:
var series = {};
for (i=0;i<axisAssignment.length;i++)
{
series[i] = {targetAxisIndex: axisAssignment[i]};
}
return series;
However, all of my data is only being written to the left axis, despite the debugger suggesting that the object is correct. My option code is below:
var options =
{
hAxis: {title: xTitle},
vAxes: {0: {title: y1Type},
1: {title: y2Type}
},
series: calculateSeries(),
pointSize: 1,
legend: {position: 'top', textStyle: {fontSize: 10}}
};
Any assistance would be greatly apreciated.
Thanks
Tom
edit: whole file for reference (it's a work in progress so a bit of a mess I'm afraid)
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart());
function drawChart()
{
var title = "Node: "+currentNode;
var xTitle = "Date";
var yTitle = titles[currentVariable];
if (totalData !== null)
{
var tempData = newData();
var tempData2 = totalData;
dataArray[dataCount] = tempData;
var joinMark = countArray(dataCount);
totalData = google.visualization.data.join(tempData2,tempData,'full',[[0,0]],joinMark,[1]);
dataCount = dataCount+1;
}
else
{
totalData = newData();
dataArray[dataCount] = totalData;
dataCount = 1;
}
var options =
{
hAxis: {title: xTitle},
vAxes: {0: {title: y1Type},
1: {title: y2Type}
},
series: calculateSeries(),
pointSize: 0.5,
legend: {position: 'top', textStyle: {fontSize: 10}}
};
var chart = new google.visualization.ScatterChart(document.getElementById('graph'));
console.log(calculateSeries());
chart.draw(totalData, options);
function countArray(count)
{
var arrayCount= new Array();
if (count===1)
{
arrayCount[0] = count;
}
else
{
for (var i=0;i<count;i++)
{
var temp = i+1;
arrayCount[i] = temp;
}
}
return arrayCount;
}
function calculateSeries()
{
var series = {};
for (i=0;i<axisAssignment.length;i++)
{
series[i] = {targetAxisIndex: axisAssignment[i]};
}
return series;
}
function newData()
{
var dataType = dataIn[0];
dataIn.shift();
var axis = dataSelect(dataType);
axisAssignment.push(axis);
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', "Node: "+currentNode+": "+titles[currentVariable]);
var num = (dataIn.length);
data.addRows(num/2);
var i = 0;
var j = 0;
while (i<num)
{
var d = (dataIn[i]);
if (i%2===0)
{
d = new Date(d);
data.setCell(j,0,d);
i++;
}
else
{
data.setCell(j,1,parseFloat(d));
i++;
j++;
}
}
return data;
}
function dataSelect(type)
{
var axisNumber;
if (y1Type === null || y1Type === type)
{
y1Type = type;
axisNumber = 0;
}
else if (y2Type === null || y2Type === type)
{
y2Type = type;
axisNumber = 1;
}
else
{
alert("You already have 2 axes assigned.\n\nPlease clear the graph \nor select more objects of \ntype"+y1Type+" or \ntype "+y2Type+" to continue.");
axisNumber = null;
}
return axisNumber;
}
}
Ok, it seems that it's an issue with my choice of ScatterChart,
var options =
{
hAxis: {title: xTitle},
series: calculateSeries(),
vAxes: {0: {title: y1Type },
1: {title: y2Type}
},
pointSize: 0.5,
legend: {position: 'top', textStyle: {fontSize: 10}}
};
var chart = new google.visualization.LineChart(document.getElementById('graph'));
chart.draw(totalData, options);
I've changed it to LineChart and it's working fine, by keeping the pointSize option, the appearance is almost completely unchanged. Thanks for your help juvian.

Google Column Chart cropping the bars

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.

Categories