So i have this function to draw a graph, i already changed it a bit to try to make the chart responsive, but im not being able to do it...
here is the function:
$(document).ready(function(){
google.charts.load('current', {'packages': ['corechart']});
//alert('aa00'~
$('.error').hide();
$(".buttonSala").click(function() {
// validate and process form here
$('.error').hide();
var nome = $( "#nomeSala option:selected" ).val();
var objeto = $( "#sensorSala option:selected" ).val();
var canal = $( "#canalSala option:selected" ).val();
var datai = $("#datainisala").val();
var dataf = $("#datafimsala").val();
//alert(canal);
// Send the data using post
var posting = $.post( "getSala.php", { canal: canal, dataini: datai, datafim: dataf, objeto: objeto } );
// Put the results in a div
posting.done(
function drawChart1( data ) {
// Set a callback to run when the Google Visualization API is loaded.
$('.box-title').html(nome);
var response = JSON.parse(data);
var jsonData = response.channels[canal].values;
var desciption = response.channels[canal].info.chname;
google.charts.setOnLoadCallback(function() {
dataArray = [["ts", desciption ]];
for (var i = 0; i < jsonData.length; i++)
{
var tempArray = [jsonData[i].ts, parseFloat(jsonData[i].value.replace(",", "."))];
dataArray.push(tempArray);
}
// Create our data table out of JSON data loaded from server.
var data = google.visualization.arrayToDataTable(
dataArray
);
var options = {
curveType: 'function',
backgroundColor: '#fff',
colors: ['#5d4a50'],
vAxis: {
gridlines: {
color: 'transparent'
},
textStyle: {
color: '#666', fontSize: 16
}
},
legend: { position: 'bottom', textStyle: {
color: '#666', fontSize: 18
} }
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
);
});
$(window).resize(function(){
drawChart1();
});
return false;
});
});
Then on my css i already added this:
.chart {
width: 100%;
min-height: 450px;
}
And my html is like this:
<div class="row">
<div class="col-md-12">
<div id="chart_div" class="chart"></div>
</div>
</div>
But the graph isn't responsive still... The div where the graph is being draw is responsive already, but when i resize the window, the graph inside just gets cut...
Any sugestions?
first, you can rely on the callback from google to know when the document is ready,
instead of --> $(document).ready(...
and the callback can be placed in the load statement,
no need to use setOnLoadCallback every time the chart needs to be drawn
recommend setup similar to the following snippet...
google.charts.load('current', {
callback: function () {
var googleChart = new google.visualization.AreaChart(document.getElementById('chart_div'));
var googleData = null;
$('.buttonSala').click(getData);
$(window).resize(drawChart);
function getData() {
$('.error').hide();
var nome = $( "#nomeSala option:selected" ).val();
$('.box-title').html(nome);
var objeto = $( "#sensorSala option:selected" ).val();
var canal = $( "#canalSala option:selected" ).val();
var datai = $("#datainisala").val();
var dataf = $("#datafimsala").val();
var posting = $.post( "getSala.php", { canal: canal, dataini: datai, datafim: dataf, objeto: objeto } );
posting.done(processData);
return false;
}
function processData(data) {
var response = JSON.parse(data);
var jsonData = response.channels[canal].values;
var desciption = response.channels[canal].info.chname;
dataArray = [["ts", desciption ]];
for (var i = 0; i < jsonData.length; i++) {
dataArray.push([
jsonData[i].ts,
parseFloat(jsonData[i].value.replace(",", "."))
]);
}
var googleData = google.visualization.arrayToDataTable(
dataArray
);
drawChart();
}
function drawChart() {
if (googleData === null) {
return;
}
googleChart.draw(googleData, {
curveType: 'function',
backgroundColor: '#fff',
colors: ['#5d4a50'],
vAxis: {
gridlines: {
color: 'transparent'
},
textStyle: {
color: '#666',
fontSize: 16
}
},
legend: {
position: 'bottom',
textStyle: {
color: '#666', fontSize: 18
}
}
});
}
},
packages: ['corechart']
});
Related
i am creating google charts and I already implement top 5 user column charts after that if you select first user column than displaying first user page history data from other variables(eachuser_data) its easy implement function in high charts! but in google charts, I don't know about add events.addListener work or not in this problem. let me know google charts provide click event on each column and display other graphs in same graph draw function. ? thank you in advance
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var charts = {};
var options = {
Column: {
chartArea: {
height: '100%',
width: '100%',
top: 24,
left: 64,
right: 32,
bottom: 48,
},
'vAxis': {
title: 'Cost in USD ($)', format:'$#',
},
height: '100%',
legend: {
position: 'bottom'
},
width: '100%'
}
};
// columns charts data
//top 5 user data with total click
var jsonData = [["johan",69],["jack",23],["scott",24],["x",5],["y",10]];
loadData(jsonData, '1', 'Column');
//specifc user data
var user1 = [["report1",45],["report2",40],["index.html",50]];
var user2 = [["report1",4],["report2",3],["index.html",5]];
var user3 = [["report1",4],["report2",3],["index.html",5]];
var user4 = [["report1",4],["report2",3],["index.html",5]];
var user5 = [["report1",4],["report2",3],["index.html",5]];
// load json data
function loadData(jsonData, id, chartType) {
// create data table
var dataTable = new google.visualization.DataTable();
// add date column
dataTable.addColumn('string', 'Total numbe of click');
var rowIndex = dataTable.addRow();
dataTable.setValue(rowIndex, 0, dataTable.getColumnLabel(0));
$.each(jsonData, function(productIndex, product) {
var colIndex = dataTable.addColumn('number', product[0]);
// add product data
dataTable.setValue(rowIndex, colIndex, product[1]);
});
// draw chart
$(window).resize(function () {
drawChart(id, dataTable);
});
drawChart(id, dataTable);
}
function drawChart(id, dataTable) {
if (!charts.hasOwnProperty(id)) {
charts[id] = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart-' + id,
options: {
vAxis: {
title: 'Cost in USD ($)',
format: '$#',
},
width: '100%',
height: '100%',
legend: {
position: 'bottom'
},
},
});
}
charts[id].setDataTable(dataTable);
charts[id].draw();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart-1"></div>
to know which column has been clicked / selected,
listen for the 'select' event
google.visualization.events.addListener(chart, 'select', chartSelection);
then use chart method getSelection() to get the row and column index of the column selected
getSelection will return an array of objects
[{row: 0, column: 1}]
the select event will fire both when a column is selected and un-selected
be sure to check the length of the array return by getSelection()
before trying to access the array contents
for column charts, only one column can be selected at a time
so the values of the selection will always be the first element in the array
function chartSelection() {
var selection = chart.getSelection();
if (selection.length > 0) {
var row = selection[0].row;
var col = selection[0].column;
var xValue = data.getValue(row, 0);
var yValue = data.getValue(row, col);
console.log('selection: ' + xValue + ' = ' + yValue);
} else {
console.log('nothing selected');
}
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['x', 'y0', 'y1'],
['A', 6, 7],
['B', 7, 9],
['C', 8, 11],
['D', 9, 11],
['E', 5, 6]
]);
var options = {
legend: {
alignment: 'end',
position: 'top'
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(container);
google.visualization.events.addListener(chart, 'select', chartSelection);
function chartSelection() {
var selection = chart.getSelection();
if (selection.length > 0) {
var row = selection[0].row;
var col = selection[0].column;
var xValue = data.getValue(row, 0);
var yValue = data.getValue(row, col);
console.log('selection: ' + xValue + ' = ' + yValue);
} else {
console.log('nothing selected');
}
}
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I am using the Google Visualization API. A chart is generated based on values from an ajax call function drawchart().
The user then inputs values in textboxes and this point is added on the chart also (function addUserPoint()). function addUserPoint2() is autogenerated and is also added onto the map. The result of adduserpoint and adduserpoint2 have a line between them.
My issue: If the user adds a new point again, the chart adds those values and the previously added points stay on the chart. I want to get rid of the results of adduserpoint and adduserpoint2 before adding a new point. How can I achieve this?
var chartData;
var options2;
function addUserPoint() {
if (chartData.getNumberOfColumns() === 2) {
chartData.addColumn('number', '');
}
var aa= $("#wbtotala").text();
var bb= $("#wbtotalb").text();
chartData.addRow([
parseFloat(bb),
null,
parseFloat(aa)
]);
myLineChart.draw(chartData, options2);
}
function addUserPoint2(){
if (chartData.getNumberOfColumns() === 2) {
chartData.addColumn('number', '');
}
myLineChart.draw(0,0, options2);
var aa2 = fweight;
var bb2= fcg;
chartData.addRow([
parseFloat(bb2),
null,
parseFloat(aa2)
]);
myLineChart.draw(chartData, options2);
}
function drawchart() {
document.getElementById('addPoint').addEventListener('click', addUserPoint, false);
document.getElementById('addPoint').addEventListener('click', addUserPoint2, false);
chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Sli');
chartData.addColumn('number', 'Weight');
for (var i = 0; i < chartdatax.length; i++) {
chartData.addRow([parseFloat(chartdatax[i]), parseFloat(chartdatay[i])]);
};
options2 = {
height: 500,
hAxis: {
title: 'AB',
gridlines: {
count: 20
}
},
vAxis: {
title: 'CD',
gridlines: {
count: 15
}
},
chartArea: {top:40, width: "70%", height: "75%"},
legend: { position: 'none' },
pointSize: 5
};
myLineChart = new google.visualization.LineChart(document.getElementById('myChart2'));
myLineChart.draw(chartData, options2);
}
Use the Below Command.Here data is the DataTable Variable.
var data = new google.visualization.DataTable();
Set chartData to an empty object in addUserPoint();
function addUserPoint() {
charData = {};
if (chartData.getNumberOfColumns() === 2) {
...
}
}
This makes sure that anytime you add a new Data, it clears the previous data and you have a fresh new dataset ;)
Following Output I am getting:
Using Charisma Library implemented my donuts chart with following code,
$(document).ready(function(){
var data = [];
var opportunities_colors = new Array();
opportunities_colors["New"] = "#999999";
opportunities_colors["Inprogress"] = "#dd5600";
opportunities_colors["Complete"] = "#73a839";
opportunities_colors["Terminate"] = "#c71c22";
opportunities_colors["Reopen"] = "#c71c22";
var opportunities_colors_option = new Array();
// alert("opportunities_colors="+opportunities_colors["New"]);
var i=0;
$("#opportunities_dropdown_id option").each(function()
{
data[i] = {};
data[i].label = $(this).text();
opportunities_colors_option.push(opportunities_colors[$(this).text()]);
data[i].data = $(this).val();
i++;
});
//donut chart
if ($("#opportunities_donutchart").length) {
$.plot($("#opportunities_donutchart"), data,
{
// colors: ["green", "red", "blue", "orange", "cyan"],
colors: opportunities_colors_option,
series: {
pie: {
innerRadius: 0.5,
show: true
}
},
legend: {
show: false
}
});
}
});
Output I am getting ,
Please help to make radius same for both charts
I am trying to work with google charts for the first time. My Json is as below
{\"cols\":[{\"id\":\"Date\",\"label\":\"Date\",\"type\":\"date\"},{\"id\":\"KeywordCount\",\"label\":\"count\",\"type\":\"number\"}],\"rows\":[{\"c\":
[{\"v\":\"new Date(2014725)\",\"f\":\"25 July 2014\"},{\"v\":\"77\",\"f\":\"77\"}]},{\"c\":
[{\"v\":\"new Date(2014724)\",\"f\":\"24 July 2014\"},{\"v\":\"101\",\"f\":\"101\"}]},{\"c\":
[{\"v\":\"new Date(2014723)\",\"f\":\"23 July 2014\"},{\"v\":\"100\",\"f\":\"100\"}]},{\"c\":
[{\"v\":\"new Date(2014722)\",\"f\":\"22 July 2014\"},
{\"v\":\"130\",\"f\":\"130\"}]}],\"p\":null}
This looks good for me, I am not able to figured it out what i am missing because i can only see an error in the chart ("undefined is not a function") . My javascript file for Google charts are
google.load('visualization', '1', { 'packages': ['corechart'] });
var postDate = $('#ReportingWall').serialize();
function drawChartAll() {
var jsonData = $.ajax({
url: '/ReportingWall/analyseStats/',
type: 'POST',
data: postDate,
dataType: 'json',
async: false,
success: function (response) {
}
}).responseText;
var data = new google.visualization.DataTable(jsonData);
console.debug(jsonData);
console.debug(data);
var chart = new google.visualization.LineChart(document.getElementById('charts_all'));
chart.draw(data, options);
var columns = [];
var series = {};
for (var i = 0; i < data.getNumberOfColumns() ; i++) {
columns.push(i);
if (i > 0) {
series[i - 1] = {};
}
}
var options = {
title: 'Keywords:',
width: 908,
legend: {
position: 'right'
},
legendFontSize: 14,
chartArea: {
left: 50,
width: '80%'
},
series: series
}
google.visualization.events.addListener(chart, 'select', function () {
var sel = chart.getSelection();
// if selection length is 0, we deselected an element
if (sel.length > 0) {
// if row is undefined, we clicked on the legend
if (sel[0].row === null) {
var col = sel[0].column;
if (columns[col] == col) {
// hide the data series
columns[col] = {
label: data.getColumnLabel(col),
type: data.getColumnType(col),
calc: function () {
return null;
}
};
// grey out the legend entry
series[col - 1].color = '#CCCCCC';
} else {
// show the data series
columns[col] = col;
series[col - 1].color = null;
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);
chart.draw(view, options);
}
}
});
}
When using dates in the DataTable JSON structure, you must omit the new keyword; you are constructing a string that the Visualization API will parse into a Date object, not constructing a Date object itself.
{
"cols":[
{"id":"Date","label":"Date","type":"date"},
{"id":"KeywordCount","label":"count","type":"number"}
],
"rows":[
{"c":[{"v":"Date(2014725)","f":"25 July 2014"},{"v":77,"f":"77"}]},
{"c":[{"v":"Date(2014724)","f":"24 July 2014"},{"v":101,"f":"101"}]},
{"c":[{"v":"Date(2014723)","f":"23 July 2014"},{"v":100,"f":"100"}]},
{"c":[{"v":"Date(2014722)","f":"22 July 2014"},{"v":130,"f":"130"}]}
],
"p":null
}
If you clean it up a bit you can see in the last row you have a useless " as last char
{"cols":[
{"id":"Date","label":"Date","type":"date"},
{"id":"KeywordCount","label":"count","type":"number"}],
"rows":[
{"c":[{"v":"new Date(2014725)","f":"25 July 2014"},{"v":"77","f":"77"}]},
{"c":[{"v":"new Date(2014724)","f":"24 July 2014"},{"v":"101","f":"101"}]},
{"c":[{"v":"new Date(2014723)","f":"23 July 2014"},{"v":"100","f":"100"}]},
{"c":[{"v":"new Date(2014722)","f":"22 July 2014"},{"v":"130","f":"130"}]}],
"p":null}"
also start with a sample similar of PHP
OR this ajax
http://www.santarosa.edu/~jperetz/projects/ajax-json/
Below is my code ,Firstly i had fetched data from database using JSON,after that i binded initial 15 rows to chart,and in setInterval function i am continually binding 1 row after interval of 1 second ,My question is without alert i.e alert("hi") i am not getting initial result,how can i get result without alert?
$(function () {
$(document).ready(function () {
var Data = "";
var dataarray = [];
var IdArray = [];
var counter = 0;
var chart;
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
var series = this.series[0];
setInterval(function () {
var i = 16 + counter;
var x = IdArray[i], // current time
y = dataarray[i];
series.addPoint([x, y], true, true);
counter = counter + 1;
}, 1000);
}
}
},
title: {`enter code here`
text: 'Live HighChart From Database'
},
xAxis: {
type: 'decimal'
},
yAxis: {
title: {
text: 'Value'
}
},
series: [{
name: 'Data from database',
data: (function () {
// generate an array of random data
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'LiveHighchart.aspx/GetData',
data: '{}',
success:
function (response) {
Data = response.d;
for (var i = 0; i < Data.length; i++) {
dataarray[i] = Data[i].random;
IdArray[i] = Data[i].Id;
}
}
});
var data = [];
alert("hi");
for (var i = 0; i < 15; i++) {
data.push({
x: IdArray[i],
y: dataarray[i]
});
}
return data;
})()
}]
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto">
</div>
</div>
</form>
</body>
</html>
I think it's because the query hasn't return the result yet - the alert is causing a pause in your app that means the result can be delivered in time. You should think about using callbacks - functions that only run when the data from your AJAX call is returned.
I Solved it myself ,code after ajax request was executing before ajax request loads data:
this line (async: false) in ajax request forced code after ajax to pause until ajax loads data