I have the following Javascript code:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['controls']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var countryPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnLabel': 'Targets',
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' },
'ui': {
'allowTyping': true,
'allowMultiple': false,
'allowNone': false,
}
},
'state': {
selectedValues: ['1970']
}
});
var jsonvalues = $.getJSON("http://localhost:5000/data", function(results) {
$.each(results, function(index) {
alert(results[index].key[1]);
});
});
$
var data = google.visualization.arrayToDataTable([
['Year','Targets', 'Total targets'],
{% for info in jsonvalues %}
['{{info['key'][1]|safe}}','{{info['key'][0]|safe}}', parseInt('{{info['value']|safe}}')],
{% endfor %}
]);
var barChart = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'curve_chart',
'options': {
'width': 800,
'height': 600,
},
'view': {
'columns': [0, 2]
}
});
var dash = new google.visualization.Dashboard(document.getElementById('dashboard'));
dash.bind(countryPicker, [barChart]);
dash.draw(data);
}
</script>
</head>
<body>
<div id="control2"></div>
<div id="curve_chart" style="width: 1920px; height: 1000px"></div>
</body>
</html>
What I am trying to achieve is to pass the getJSON data that I retrieve with the Ajax call from http://localhost:5000/data to the Google Chart.
I tried a lot of things but so far I am stuck and don't really know how to achieve what I want. I just inserted the alert aspect as test to see if this returns the data. The alert gives me back the JSON data that I am requesting, so that's fine.
MY JSON Data looks as follow:
[
{
key: [
"Abortion Related",
1977
],
value: 4
},
{
key: [
"Abortion Related",
1978
],
value: 6
}
]
Getting back to the question I had yesterday, solved it with the following working code:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['controls']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var countryPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnLabel': 'Targets',
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' },
'ui': {
'allowTyping': true,
'allowMultiple': false,
'allowNone': false,
}
},
'state': {
selectedValues: ['1970']
}
});
function updateDiv() {
$(document).ready(function(){
var data = new google.visualization.DataTable();
data.addColumn('number', 'Year');
data.addColumn('string', 'Targets');
data.addColumn('number', 'Total Targets');
values = new Array;
$.getJSON("http://localhost:5000/data", function(results)
{
$.each(results, function(index)
{
values.push([results[index].key[1],results[index].key[0],results[index].value]);
});
data.addRows(values);
var barChart = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'curve_chart',
'options': {
'width': 800,
'height': 600,
},
'view': {
'columns': [0, 2]
}
});
var dash = new google.visualization.Dashboard(document.getElementById('dashboard'));
dash.bind(countryPicker, [barChart]);
dash.draw(data);
});
}); } setInterval(updateDiv, 5000)
}
</script>
</head>
<body>
<div id="control2"></div>
<div id="curve_chart" style="width: 1920px; height: 1000px"></div>
</body>
</html>
First I changed from arrayToDatatable to DataTable. After that I declared the columns and
the type of data with data.addColumn. Then I moved the getJSONwithin the `var data. And that did the trick for me. More information can be found over here: https://developers.google.com/chart/interactive/docs/reference
Related
I have basically developed my own script modifying this one and querying a google Sheet instead of building the chart using static data:
https://jsfiddle.net/hisham91/3rnd80m4/
This reference link does pretty the same:
http://bl.ocks.org/battlehorse/1122276
I am able to set another background color for each chart adding the option backgroundColor but what I do not really get is to change the font color. So if for example I made the background black there is no way for me to have the text displayed in white.
<html><head>
<title>Portal Counts</title>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="portalCount_test2.js"></script>
<script>
google.load('visualization', '1.1', {'packages':['controls','linechart']});
google.setOnLoadCallback(initialize);
function initialize() {
var queryString = encodeURIComponent('SELECT A, H, O, Q, R, U LIMIT 5 OFFSET 8');
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1XWJLkAwch5GXAt_7zOFDcg8Wm8Xv29_8PWuuW15qmAE/gviz/tq?sheet=Sheet1&headers=1&tq=' + queryString);
query.send(drawDashboard);
}
function drawDashboard(response) {
var data = response.getDataTable();
var filterPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter1_div',
'options': {
'filterColumnLabel': 'LinearOptimizationSheet',
'fontcolor': '#ffffff',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
var testChart = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'chart1_div',
'options': {
'title': 'Test Chart',
'height': 400,
'backgroundColor': '#000000',
'colors': ['#00c2ff', '#28f428'],
},
});
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard1_div'));
dashboard.bind(filterPicker, testChart);
dashboard.draw(data);
}
</script>
</head>
<body bgcolor="#000000">
<div align="center">
<div id="dashboard1_div">
<div id="filter1_div"></div>
<div id="filter2_div"></div>
<div id="chart1_div" style="width:100%;"></div>
</div>
</div>
</div>
</body>
</html>
I tried every solution found here and on the web without success. Maybe soneone can help. Thanks in advance.
<html><head>
<title>Portal Counts</title>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {'packages':['corechart', 'controls']});
google.charts.setOnLoadCallback(initialize);
function initialize() {
var queryString = encodeURIComponent('SELECT A, H, O, Q, R, U LIMIT 5 OFFSET 8');
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1XWJLkAwch5GXAt_7zOFDcg8Wm8Xv29_8PWuuW15qmAE/gviz/tq?sheet=Sheet1&headers=1&tq=' + queryString);
query.send(drawDashboard);
}
function drawDashboard(response) {
var data = response.getDataTable();
var filterPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter1_div',
'options': {
'filterColumnLabel': 'LinearOptimizationSheet',
'fontcolor': '#ffffff',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
var testChart = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'chart1_div',
'options':
{
'title': 'Test Chart',
'height': 400,
'backgroundColor': '#000000',
'colors': ['#00c2ff', '#28f428'],
titleTextStyle:
{
color: '#FFFFFF'
},
hAxis:
{
textStyle:
{
color: '#FFFFFF'
},
titleTextStyle:
{
color: '#FFFFFF'
}
},
vAxis: {
textStyle:
{
color: '#FFFFFF'
},
titleTextStyle:
{
color: '#FFFFFF'
}
},
legend:
{
textStyle:
{
color: '#FFFFFF'
}
}
}
});
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard1_div'));
dashboard.bind(filterPicker, testChart);
dashboard.draw(data);
}
</script>
</head>
<body bgcolor="#000000">
<div align="center">
<div id="dashboard1_div">
<div id="filter1_div"></div>
<div id="filter2_div"></div>
<div id="chart1_div" style="width:100%;"></div>
</div>
</div>
</div>
</body>
</html>
use series for chart lines. for more information look through this link
https://developers.google.com/chart/interactive/docs/lines
use haxis, vaxis, legend textStyle & titleTextStyle for side text
(Google Visualization API font color)
another, extreme way, using f12 and changing element attribute value manually, for example: $('path').attr('stroke', 'blue') - to change lines color
UPDATE :
i've removed my example and post your code after refactoring. check it up
I'm having trouble displaying google sheets info on the dashboard. The x and y-axis labels show up like Generalxxx . The data is from here .
var laptimeChart = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'chart_div',
'width': '500',
'height': '500',
'view': { 'columns': [1,2] }
});
the chart seems to be using the "General" format by default
to correct, set a specific format for each axis...
options: {
hAxis: {
format: '0'
},
vAxis: {
format: '#,##0'
}
},
see following working snippet...
google.charts.load('current', {
packages: ['controls', 'corechart', 'table']
}).then(function () {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1PlT8k6qXsCkOCEEJFn7apKYgDunLi1Lzmnmo_AKQBXc/edit#gid=0');
query.send(handleQueryResponse);
function handleQueryResponse(response) {
if (response.isError()) {
console.log('Error: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var control = new google.visualization.ControlWrapper({
controlType: 'NumberRangeFilter',
containerId: 'control',
options: {
filterColumnIndex: 1,
ui: {
format: {
pattern: '0'
}
}
}
});
var chart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart',
options: {
hAxis: {
format: '0'
},
vAxis: {
format: '#,##0'
}
},
view: {
columns: [1, 2]
}
});
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard'));
dashboard.bind(control, chart);
dashboard.draw(data);
}
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard">
<div id="control"></div>
<div id="chart"></div>
</div>
I would like to make a filter by company.
However, all the Strings from my database values are NaN picture
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', { packages : ['controls'] } );
function createTable() {
// JSON request
var jsonData = $.ajax({
url: 'http://getdata',
type: 'POST',
dataType: 'json'
}).done(function (results) {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Performance_date');
data.addColumn('number', 'Performance_company');
data.addColumn('number', 'Performance_zone');
data.addColumn('number', 'Entradas');
$.each(results, function (i, row) {
data.addRow([new Date((row.performance_date)),parseInt(row.performance_company),parseInt(row.performance_zone),parseInt(row.performance_profit)]);
});
// Define category pickers for 'Companies'
var myFields = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'company_div',
'options': {
'filterColumnLabel': 'Performance_company',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
How can I change / update an existing google chart's options. Let's say I want to with a click of a button apply these options to an existing chart:
var options = {
width: 400,
height: 240,
title: 'Toppings I Like On My Pizza',
colors: ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6']
};
and yes, I do know that you can do al this with the chartEditor but that solution will not work for me in this case
If your chart is a ChartWrapperin a Dashboard, you may be inspired by
https://developers.google.com/chart/interactive/docs/gallery/controls#8-programmatic-changes-after-draw
google.charts.load('current', {
'packages': ['corechart', 'controls']
});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var dashboard = new google.visualization.Dashboard(
document.getElementById('programmatic_dashboard_div'));
var programmaticSlider = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'programmatic_control_div',
'options': {
'filterColumnLabel': 'Donuts eaten',
'ui': {
'labelStacking': 'vertical'
}
}
});
// We omit "var" so that programmaticChart is visible to changeOptions().
programmaticChart = new google.visualization.ChartWrapper({
'chartType': 'PieChart',
'containerId': 'programmatic_chart_div',
'options': {
'width': 300,
'height': 300,
'legend': 'none',
'chartArea': {
'left': 15,
'top': 15,
'right': 0,
'bottom': 0
},
'pieSliceText': 'value'
}
});
var data = google.visualization.arrayToDataTable([
['Name', 'Donuts eaten'],
['Michael', 5],
['Elisa', 7],
['Robert', 3],
['John', 2],
['Jessica', 6],
['Aaron', 1],
['Margareth', 8]
]);
dashboard.bind(programmaticSlider, programmaticChart);
dashboard.draw(data);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<button onclick="changeOptions();">
Change Options
</button>
<script type="text/javascript">
function changeOptions() {
programmaticChart.setOptions({
width: 400,
height: 240,
title: 'Toppings I Like On My Pizza',
colors: ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6']
});
programmaticChart.draw();
}
</script>
<div id="programmatic_dashboard_div">
<div id="programmatic_control_div"></div>
<div id="programmatic_chart_div"></div>
</div>
Call the draw() function with the new options
google.charts.load('current', {
packages: ['corechart', 'bar']
});
google.charts.setOnLoadCallback(drawBasic);
var changeOptions; // global variable for callback function
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'X');
data.addColumn('number', 'Quantity');
data.addRows([
['one',5],
['two',15],
['three',8]
]);
var options = {
title: 'Original Title',
};
var chart = new google.visualization.ColumnChart(
document.getElementById('chart_div'));
chart.draw(data, options);
// function to change options on button click
changeOptions = function() {
// define new options
options.width = 200;
options.height = 200;
options.title = 'Toppings I Like On My Pizza';
options.colors = ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6'];
// call draw() with new options
chart.draw(data, options);
}
}
<script src="//www.gstatic.com/charts/loader.js"></script>
<button onclick="changeOptions();">change options</button>
<div id="chart_div"></div>
When I hover over a point in my line chart/graph I get only the Y value and not the X value.
What I get:
36
Speed: 120
What I want:
Distance: 36
Speed: 120
Code:
<script type="text/javascript" src="https://www.google.com/jsapi" ></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', "Distance");
data.addColumn('number', "Speed");
data.addRows(<?php echo json_encode($DistanceSpeedArray, JSON_NUMERIC_CHECK); ?>);
var options = {
focusTarget: 'category',
backgroundColor: 'none',
chartArea: {
backgroundColor: 'transparent',
left: 40,
top: 40,
width: 1200,
height: 350
},
legend: {
position: 'top'
},
hAxis: {title: 'Distance (KM)', titleTextStyle: {color: 'black'}},
//vAxis: {title: 'Speed (KM/H)', titleTextStyle: {color: 'black'}},
colors: ['green'],
crosshair: {
orientation: 'vertical'
},
animation: {
startup: true,
duration: 5000
},
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
The above code is a complete code including the focusTarget: 'category' which still returns only the Y title. I have also included a screenshot.
You may apply a format to the Distance-column
new google.visualization.PatternFormat("Distance: {0}")
.format(data, [0], 0);
https://jsfiddle.net/6tf2fatz/
Basically you need to add focusTarget: 'category' for focus on a grouping of all data points along the major axis.
Try below code,
<script type="text/javascript" src="https://www.google.com/jsapi" ></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Distance');
data.addColumn('number', "Speed");
data.addRows(<?php echo json_encode($DistanceSpeedArray, JSON_NUMERIC_CHECK); ?>);
...
var options = { focusTarget: 'category' };
var chart = new google.visualization.LineChart(document.getElementById('your_div_chart'));
chart.draw(data, options);
}