I have this 2 googlecharts in my program:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var matrix = [];
for(var i=0; i<50; i++) {
matrix[i] = new Array(2);
}
var j=0;
$.getJSON("x.json",function(data){
$.each(data, function(key, val){
matrix[j][0]=(val.y);
matrix[j][1]=(val.z);
j++;
});
});
// Draw the chart and set the chart values
function drawChart() {
var data = google.visualization.arrayToDataTable([
['a', 'b'],
[matrix[0][0], matrix[0][1]],
[matrix[1][0], matrix[1][1]],
[matrix[2][0], matrix[2][1]],
[matrix[3][0], matrix[3][1]],
[matrix[4][0], matrix[4][1]]
]);
// Set chart options
var options = {'title':'h',
'width':900,
'height':400,
is3D: true,
};
// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
var matrix = [];
for(var i=0; i<50; i++) {
matrix[i] = new Array(2);
}
var j=0;
$.getJSON("x.json",function(data){
$.each(data, function(key, val){
matrix[j][0]=(val.y);
matrix[j][1]=(val.z);
j++;
});
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Element", "Density", { role: "style" } ],
[matrix[0][0], matrix[0][1], "red"],
[matrix[1][0], matrix[1][1], "yellow"],
[matrix[2][0], matrix[2][1], "green"],
[matrix[3][0], matrix[3][1], "grey"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "k",
width: 800,
height: 300,
bar: {groupWidth: "95%"},
legend: { position: "none" }
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
<!--options-->
}
</script>
<div id="columnchart_values" style="width: 900px; height: 800px; display: inline-block;"></div>
</div>
I want to change the background color of both.
I've tryed some of the solutions for background color change, like adding the background color to the options, adding a chart area and using the chart.draw(data, google.charts.Bar.convertOptions(options)) method.
But the chart simple disapears.
Any solution for this?
You can change Google Chart Color By write in backgroundColor in your option, for example -by using your code-:
var options = {
'backgroundColor': 'blue',
};
var chart = new
google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
for your first snippet code, you can check this work color in fiddle
Related
I have flask app with
#app.route('/dash_data')
def dash_data():
***
return jsonify({'key' : dashDetails})
which return nice json string
{"key":[["Food",50],["Health",10],["Restaurants",2],["Sports",20],["Taxi",5]]}
My google chart script expects
[
['Food', 50],
['Health', 10],
['Restaurants', 2],
['Sports', 20],
['Taxi', 5]
]
and it has the following way to pass this data to the chart:
var testData = $.get('/dash_data');
var tm = test_data.done(function (resp){ return resp;})
var dataArray = tm.responseJSON.key
var data = google.visualization.arrayToDataTable(dataArray);
However, the console output is
Uncaught (in promise) TypeError: Cannot read property 'key' of undefined at drawChart
Where is my mistake?
The full google-chart js file:
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var test_data = $.get('/dash_data');
var tm = test_data.done(function (resp){return resp;})
var t = tm.responseJSON.key
var data = google.visualization.arrayToDataTable(t);
var options = {
title: 'Expences 12.2020',
pieHole: 0.4,
width: 380,
height: 200
};
var chart = new google.visualization.PieChart(document.getElementById('exp_month_chart'));
chart.draw(data, options);
}
Thank you.
$.get runs asynchronously,
so you need to wait for the done callback before trying to draw the chart...
google.charts.load("current", {
packages: ["corechart"]
}).then(function () {
$.get('/dash_data').done(function (resp) {
var data = google.visualization.arrayToDataTable(resp.key);
var options = {
title: 'Expences 12.2020',
pieHole: 0.4,
width: 380,
height: 200
};
var chart = new google.visualization.PieChart(document.getElementById('exp_month_chart'));
chart.draw(data, options);
});
});
in the post above,
var t = tm.responseJSON.key
runs before
var tm = test_data.done(function (resp){return resp;})
is finished...
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 have a line chart to draw multi values but it's drawing extra line with angles, I have checked my data there are no duplicates. this is how it looks like :
my chart options are simple:
var options = {
"legend": { "position": "top"},
"hAxis": {
title: "Time of Day"
},
vAxis: {
"textPosition": "out",
textStyle: {color: '#328332'},
title: "Voltage (V)",
titleTextStyle: {color: '#328332'},
}
}
var chartId = 'records-chart';
var dt = new google.visualization.DataTable();
dt.addColumn('datetime', 'Date');
dt.addColumn('number', 'Voltage');
var data = [];
for (var i = 0; i < $scope.data.length; i++) {
data[i] = [
$scope.data[i].time,
$scope.data[i].voltage,
];
}
dt.addRows(data);
var chart = new google.visualization.LineChart(document.getElementById(chartId));
chart.draw(rtRecordsDataTable, options);
why is the chart connecting data in this weird behaviour ? what can I do to avoid it?
looks like you need to sort the data by the first column (date),
before drawing the chart...
dt.addRows(data);
dt.sort([{column: 0}]);
var chart = new google.visualization.LineChart(document.getElementById(chartId));
chart.draw(rtRecordsDataTable, options);
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 ;)
I want to show google chart using data that i acquired from SQL server using javascript. But i got IE error "Unable to get property arrayToDataTable" even i already add google chart JS. I already check the data by alert it, and the data is ok. How to fix this?
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var array = loadData();
google.load("visualization", "1.1", {packages:["bar"]});
google.setOnLoadCallback(drawChart(array));
function loadData(){
var array = [
['Year', 'Sales', 'Expenses', 'Profit']
];
//Connection
var connection = new ActiveXObject("ADODB.Connection") ;
var connectionstring="Provider=SQLOLEDB.1;Password=Password1234;Persist Security Info=True;User ID=sa;Initial Catalog=all_data;Data Source=172.16.11.90";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open("SELECT * FROM bar_chart", connection);
rs.MoveFirst;
while(!rs.eof)
{
array.push([rs.fields(0), parseInt(rs.fields(1)), parseInt(rs.fields(2)), parseInt(rs.fields(3))]);
rs.movenext;
}
rs.close;
connection.close;
return array;
}
function drawChart(x) {
alert(x[4][3]);
var data = google.visualization.arrayToDataTable(x);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017'
},
bars: 'horizontal' // Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data, options);
}
</script>
And here is my html:
<body>
<div id="barchart_material" style="width: 900px; height: 500px;"></div>
</body>
This error occurs since google.setOnLoadCallback function expects a callback as an argument.
Replace:
var array = loadData();
google.setOnLoadCallback(drawChart(array));
In this case drawChart function is invoked immediately without
waiting google visualization API to load
with:
google.setOnLoadCallback(function () {
var array = loadData();
drawChart(array);
});
Example
google.load("visualization", "1.1", { packages: ["bar"] });
google.setOnLoadCallback(function () {
var data = generateData();
drawChart(data);
});
function generateData() {
var data = [
['Year', 'Sales', 'Expenses', 'Profit']
];
for (var year = 2000; year < 2010; year++) {
data.push([year.toString(), getRandomArbitrary(100, 200), getRandomArbitrary(100, 400), getRandomArbitrary(100, 500)]);
}
return data;
}
function drawChart(data) {
var dataTable = google.visualization.arrayToDataTable(data);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017'
},
bars: 'horizontal' // Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(dataTable, options);
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="barchart_material" style="width: 900px; height: 500px;"></div>