Google Visualization API - save and retrieve ChartWrapper object - javascript

Looking to save the ChartWrapper object after a chart has been modified in the Google Visualization Chart Editor so that the page reloads the last chart they selected is shown rather the default set in the options.
I have managed to save a JSON.stringfy representation of the ChartWrapper object using the code below:
function getWrapper() {
chart = chartEditor.getChartWrapper();
localStorage.setItem('chartWrapper', JSON.stringify(chart));
redrawChart();
}
The code for the default chart is provided below:
chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chart_div',
dataTable: data,
options: {
title: '#Html.Raw(Model.KeyIndicatorName)',
hAxis: {
slantedText: true,
slantedTextAngle: 30,
title: 'Reporting Period'
},
vAxis: {
title: '#Model.XAxis'
},
chartArea: {
top: 40,
width: "65%"
},
pointSize: 5
}
});
on reload if the localStorage item is available I want default options to be superseded with the those values.
How I go about implementing this?

need to use chart wrapper method toJSON method, not JSON.stringify...
function getWrapper() {
chart = chartEditor.getChartWrapper();
localStorage.setItem('chartWrapper', chart.toJSON());
redrawChart();
}
then you can create the chart directly from the json...
var chart = new google.visualization.ChartWrapper(localStorage.getItem('chartWrapper'));

Related

How can I enlarge text size of google bar chart and show x value on each bar?

Good morning everyone,
I have a problem about the size of bar chart values. The x values goes like 0,5,10,15,20,23 five by five but I want it to be like 0,1,2,3 one by one.
Another issue is, I want y values to be shown on top of each bar. If 23th bar's value is 10 it must be shown on the top of 23th bar because people should easily see the chart values from the distant.
And my last question is I want to enlarge the size of x and y values of chart but I could only enlarge labels. I couldn't find the right option.
Oh almost I forgot, I have another problem about legend. If legend is on the right side, the chart is getting smaller but I can't move legend to top or bottom. Even in the code says legend bottom it shows on the right.
my codes are here
function drawPaLoChart() {
var data = [['Hours', 'Label1', 'Label2']];
for (var i=0; i<pageload.length;i++){
data.push([pageload[i][0], pageload[i][1], pageload[i][2] ]);
}
var data = google.visualization.arrayToDataTable(data);
var options = {
'fontSize': 30,
chart: {
'width': 600,
title: 'Hourly Page Load Times',
},
legend: { position: 'bottom' },
bar: { groupWidth: "100%" },
backgroundColor: {fill: 'transparent'},
chartArea: {
backgroundColor: 'transparent'
},
'tooltipFontSize':22
};
var chart = new google.charts.Bar(document.getElementById('palochart'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
to add labels to the bar, you need to add an annotation column role to the data table.
however, you are using a material bar chart.
column roles, along with several other options, are not supported by material charts.
see --> Tracking Issue for Material Chart Feature Parity
material = google.charts.Bar -- packages: ['bar']
classic = google.visualization.ColumnChart -- packages: ['corechart']
using a classic chart, we can use a data view to add the annotation column role.
see following snippet...
function drawPaLoChart() {
var data = [
['Hours', 'Label1', 'Label2']
];
for (var i = 0; i < pageload.length; i++) {
data.push([pageload[i][0], pageload[i][1], pageload[i][2]]);
}
var data = google.visualization.arrayToDataTable(data);
var options = {
fontSize: 30,
width: 600,
title: 'Hourly Page Load Times',
legend: {
position: 'bottom'
},
bar: {
groupWidth: "100%"
},
backgroundColor: {
fill: 'transparent'
},
chartArea: {
backgroundColor: 'transparent'
},
tooltipFontSize: 22
};
var chart = new google.visualization.ColumnChart(document.getElementById('palochart'));
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
role: 'annotation',
type: 'string'
}]);
// use data view to draw chart
chart.draw(view, options);
}

Color issues in Google Charts Bar

I can not generate different colors in google charts bars. The data is coming from a variable data.addRows([[${golLog}]]); and I realized that inside this variable has an array. It looks like he throws only the first color for the two bars.
Here is code for understanding:
google.charts.load('current', {
'packages' : [ 'corechart','bar' ]
});
google.charts.setOnLoadCallback(golLog);
function golLog() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Qtd');
data.addColumn('number');
data.addRows([[${golLog}]]);
var options = {
chart: {
left:0,
top:40,
width:'100%',
height:'100%'
},
title: 'GOL',
legend: { position: 'none' },
theme: 'material',
fontSize: 20,
colors:['#fc1700','#212e84']
};
var chart = new
google.charts.Bar(document.getElementById('chart_golLog'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
<div id="chart_golLog"></div>
Image
Dados que estão na variável

Why does a spurios alert() cause Google Chart to draw correctly?

I'm trying to draw two Google Charts on the same webpage.
The code for the 2nd chart looks like this
function chart2() {
/* second chart (scatter plot) */
var data2 = new google.visualization.DataTable();
data2.addColumn('number', 'Date');
data2.addColumn('number', 'Sold Price');
var map = /*[[${worthTemplateData.pricingInfo['marketHistory']}]]*/ [];
map.forEach(function (item) {
data2.addRows([ [item.date, item.origPrice] ]);
});
alert('Please wait');
var options = {
width: 900,
height: 500,
chart: {
title: 'Price History',
subtitle: 'For similar-size units'
},
hAxis: {title: 'Date'},
vAxis: {title: 'Sold Price'}
};
var chart2 = new google.charts.Scatter(document.getElementById('google-chart2'));
chart2.draw(data2, google.charts.Scatter.convertOptions(options));
}
It works.
But as soon as I remove the alert('Please wait'); line, it doesn't work anymore! The screen area where the chart should be is empty.
I suspect there is some timing issue, even though JS is presumably "single-threaded".
What's more puzzling, if I change the order, only the other chart loads:
google.load("visualization", "1.0", {packages: ["bar", "scatter"]});
google.setOnLoadCallback(drawCharts);
function drawCharts() {
chart2();
chart1();
}
What's the fix?
There is an issue with drawing multiple material charts.
You could switch to Classic Scatter Charts: google.charts.Scatter -> google.visualization.ScatterChart or try with some delay:
function doSetTimeOutDrawChart(chart, data, options, delay){
setTimeout(function () {
chart.draw(data, options);
}, delay);
}
like in this example:
jsFiddle

Google Charts backgroundColor not working with example code

I use code from example page to create horizontal bars chart:
Option backgroundColor work for other chart types, like this and that.
Is there are way to change background color for Bars charts?
google.load('visualization', '1.1', {packages:['bar']});
function drawVisualization() {
// Create and populate the data table.
var data = new google.visualization.arrayToDataTable([
['Opening Move', 'Percentage'],
["King's pawn (e4)", 44],
["Queen's pawn (d4)", 31],
["Knight to King 3 (Nf3)", 12],
["Queen's bishop pawn (c4)", 10],
['Other', 3]
]);
var options = {
backgroundColor: { fill: '#000' },//this is not working
title: 'Chess opening moves',
width: 900,
legend: { position: 'none' },
chart: { title: 'Chess opening moves',
subtitle: 'popularity by percentage' },
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'Percentage'} // Top x-axis.
}
},
bar: { groupWidth: "90%" },
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, options);
}
google.setOnLoadCallback(drawVisualization);
<script src="http://www.google.com/jsapi?fake=.js"></script>
<div id="top_x_div"></div>
chart
You're using a Material Bar chart (See the relevant documentation here.)
See the comment at the end of the documentation paragraph :
The Material Charts are in beta. The appearance and interactivity are
largely final, but the way options are declared is not. If you are
converting a Classic Bar Chart to a Material Bar Chart, you'll want to
replace this line:
chart.draw(data, options);
...with this:
chart.draw(data, google.charts.Bar.convertOptions(options));
So if you want your standard options taken into account you need to wrap them with google.charts.Bar.convertOptions().
Have a try, it works great. See a jsfiddle of it here.

Google Charts API: Always show the Data Point Values using arrayToDataTable. How?

First I'd like to let it be known that although there is a similar question labeled:
Google Charts API: Always show the Data Point Values in Graph
...on the site, I can't seem to use it's solution since my chart is fed using arrayToDataTable.
Here's my code:
function drawChart1998() {
var data = google.visualization.arrayToDataTable([
['Year', 'Index Trend'],
['1/3', 1236777],
['1/7', 834427],
['1/10', 2164890],
['1/14', 1893574],
['1/17', 2851881],
['1/21', 359504],
['1/24', 2264047],
['1/28', 3857933],
['1/31', 2197402],
['2/4', 2469935],
['2/7', 1651752],
['2/11', 4710582],
['2/14', 1565803],
['2/18', 345499],
['2/21', 2817319],
['2/25', 733242],
['2/28', 1485788],
['3/4', 1091181],
['3/7', 4477498],
['3/11', 490931],
['3/14', 3905556],
['3/18', 475417],
['3/21', 1512729],
['3/25', 1782796],
['3/28', 4778434]
]);
var options = {
curveType: "function",
title: '1998 Results',
vAxis: {viewWindow: {min: 0, max: 5006386}},
hAxis: {textStyle: {color: 'black', fontName: 'verdana', fontSize: 10} },
series: {0: { pointSize: 6 }}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_1998'));
chart.draw(data, options);
}
As you can see, I managed to set the series to display the DataPoint dots but I can't seem to figure out how to incorporate the following line of code as the previous post on the site suggests in order to display the values for each DataPoint.
data.addColumn({type: 'string', role: 'annotation'});
For reference, you can input an annotation column to your DataTable using the arrayToDataTable method. Pass an object instead of a string for the column header:
var data = google.visualization.arrayToDataTable([
[/* column headers */, {type: 'string', role: 'annotation'}, /* column headers */],
// ...
]);
This works for any column role.
If you just want to display the value of a data point, you don't have to add an extra column to your DataTable. You can use a DataView to add an "annotation" column, calculated as the string-value of a source column:
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: 'string',
role: 'annotation',
sourceColumn: 1,
calc: 'stringify'
}]);
Then draw the chart using the view instead of the DataTable:
chart.draw(view, options);

Categories

Resources