I'm having trouble coming up with a function that will animate a single column bar inside of my chart when I use a slider going back and forth..left and right.. I have read the animation docs on the Google Charts API documentation, but I am having a hard time understanding what I need to do.
Here is my code so far. Where would I start in figuring out how to animate just one of my bars using a slider I have made in titanium? I call the function updateChart() from my app.js file using the evalJS function. I have verified it works, by doing a console.log when my slider goes back and forth. I just can't seem to wrap my head around it how to apply this to animating a single column bar. Any thoughts are appreciated.
Set up Google Charts on my html page.
<script type="text/javascript" src ="https://www.google.com/jsapi" > </script>
<script type="text/javascript ">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Importance');
data.addColumn('number', 'Earning');
data.addColumn({type: 'string', role: 'style'});
data.addRows([['',5,'#000000'], ['',5,'#ffffff'],['',5,'#666666'],['', 5,'#cccccc']]);
var options =
{
width: 200,
height: 240,
legend: {
position: 'none'
},
chartArea: {
backgroundColor: 'none'
},
bar: {
groupWidth: '100%'
},
animation: {
duration: 1000,
easing: 'out'
}
};
function updateChart() {
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
EDITED CODE:
<script type="text/javascript" src ="https://www.google.com/jsapi" > </script>
<script type="text/javascript ">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Importance');
data.addColumn('number', 'Earning');
data.addColumn({type: 'string', role: 'style'});
data.addRows([['',5,'#000000'], ['',5,'#ffffff'],['',5,'#666666'],['', 5,'#cccccc']]);
var options = {
width: 200,
height: 240,
legend: {
position: 'none'
},
chartArea: {
backgroundColor: 'none'
},
bar: {
groupWidth: '100%'
},
animation: {
duration: 1000,
easing: 'out'
}
};
function updateChart(value) {
data.setValue(0, 1, value);
chart.draw(data, options);
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Slider Hook Code in separate file (app.js) Titanium Platform
var sliderBarOne = Titanium.UI.createSlider({
top: '310',
left: '610',
min: '0',
max: '10',
width: '37%',
value: '5',
backgroundImage: 'assets/sliderBar.png'
});
sliderBarOne.addEventListener('change', function(e) {
chartView.evalJS("updateChart('" + e.value + "');");
});
You need to hook up an event listener for your slider that calls the updateChart function. The updateChart function should get the value from the slider and change the value in the DataTable, then cal the chart's draw method. How you hook up an event listener to the slider is going to depend on the library you are using for the slider. Here's some example code that assumes your slider object has a change method to set a change event handler and a `getValue method to get the value of the slider:
[edit: added in your slider code]
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Importance');
data.addColumn('number', 'Earning');
data.addColumn({type: 'string', role: 'style'});
data.addRows([
['',5,'#000000'],
['',5,'#ffffff'],
['',5,'#666666'],
['', 5,'#cccccc']
]);
var options = {
width: 200,
height: 240,
legend: {
position: 'none'
},
chartArea: {
backgroundColor: 'none'
},
bar: {
groupWidth: '100%'
},
animation: {
duration: 1000,
easing: 'out'
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
function updateChart(value) {
data.setValue(0, 1, value);
chart.draw(data, options);
}
// create slider
var sliderBarOne = Titanium.UI.createSlider({
top: '310',
left: '610',
min: '0',
max: '10',
width: '37%',
value: '5',
backgroundImage: 'assets/sliderBar.png'
});
sliderBarOne.addEventListener('change', function(e) {
updateChart(e.value);
});
chart.draw(data, options);
}
Related
I have The following problem related with ColumnChart (https://developers.google.com/chart/interactive/docs/gallery/columnchart).
If the label (when you mouse hover into any columns that looks like a tooltip) is set as a number, all 2000 items shows correctly. But if the label is set as a string it only shows 289 items in the chart and it is missing 1711 columns for an unknown reason.
I have this code (Label set with String, only shows 289 items instead of 2000):
http://jsfiddle.net/c809mbjx/11/
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string' ,'Day');
data.addColumn('number', 'Matches');
var dataArray = []
let number = 2000
data.addRows(number);
for (var i = 0; i < number;i++) {
data.setCell(i,0,"aaa_"+i)
data.setCell(i,1,i);
}
//var data = new google.visualization.arrayToDataTable(dataArray);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
colors: ['#0095e8'],
hAxis: {textPosition: 'none'},
vAxis: {minValue: 0, viewWindow: {min: 0}},
legend: 'none',
animation: {duration: 10000, easing: 'out'}
};
chart.draw(view, options);
}
google.load('visualization', '1', {packages: ['corechart'], callback: drawChart});
And this code (Label set with Number and works correctly):
http://jsfiddle.net/c809mbjx/12/
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number' ,'Day');
data.addColumn('number', 'Matches');
var dataArray = []
let number = 2000
data.addRows(number);
for (var i = 0; i < number;i++) {
data.setCell(i,0,i)
data.setCell(i,1,i);
}
//var data = new google.visualization.arrayToDataTable(dataArray);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
colors: ['#0095e8'],
hAxis: {textPosition: 'none'},
vAxis: {minValue: 0, viewWindow: {min: 0}},
legend: 'none',
animation: {duration: 10000, easing: 'out'}
};
chart.draw(view, options);
}
google.load('visualization', '1', {packages: ['corechart'], callback: drawChart});
we can use numbers on the x-axis and still display the string on the tooltip.
which can be accomplished by setting the last argument of the setCell method --> formattedValue
setCell(rowIndex, columnIndex, value, formattedValue)
the tooltip will display the formatted value by default.
so we provide the number as the value, and our own string as the formatted value.
data.setCell(i,0,i,"aaa_"+i);
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number' ,'Day');
data.addColumn('number', 'Matches');
let number = 2000;
data.addRows(number);
for (var i = 0; i < number;i++) {
data.setCell(i,0,i,"aaa_"+i);
data.setCell(i,1,i);
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
colors: ['#0095e8'],
hAxis: {textPosition: 'none'},
vAxis: {minValue: 0, viewWindow: {min: 0}},
legend: 'none',
animation: {duration: 10000, easing: 'out'}
};
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
note: the version of google charts loaded using jsapi has been deprecated and should no longer be used.
instead, use loader.js, this will only change the load statement.
see above snippet...
Could anyone let me know which is the best method to show/hide line legends (If using a checkbox for changing the visibility).
I should be having maximum 7 legends in line chart.
My code is below:
function DrawGraph(chartsdata, title, charttype) {
//debugger;
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(DrawChart);
function DrawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', '');
data.addColumn('number', '');
try {
var data = google.visualization.arrayToDataTable(chartsdata);
}
catch (e) {
//debugger;
//document.writeln(e);
}
var optionsBar = {
title: title,
isStacked: true,
hAxis: {
type: "datetime",
showTextEvery: 1,
ticks: [2016,2017,2018,2019,2020,2021,2022,2023]
},
legend: {
position: 'bottom',
textStyle: { fontSize: 12 }
}
};
var optionsLine = {
title: title,
//width: 500,
seriesType: 'line',
legend: {
position: 'bottom',
textStyle: { fontSize: 11 }
}
};
if (charttype == "line") {
var chart = new google.visualization.LineChart(document.getElementById('chartdiv'));
chart.draw(data, optionsLine);
}
else {
var chart = new google.visualization.ColumnChart(document.getElementById('chartdiv'));
chart.draw(data, optionsBar);
}
}
}
Toggle the legend by using none/bottom as the position:
legend: {position: 'none'} //to hide
I have a Google Chart that displays some data.
Here is the HTML -
<div id="chart"></div>
Here is the CSS -
html,
body {
width: 100%;
height: 100%;
}
#chart {
width: 100%;
}
Here is the JS -
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:B");
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
var data = response.getDataTable();
var chartAreaHeight = data.getNumberOfRows() * 10;
var chartHeight = chartAreaHeight + 70;
var options = {
title: "Andaman & Nicobar Islands",
legend: "none",
vAxis: {
title: "Year",
format: "0",
},
hAxis: {
title: "Rainfall (in mm)"
},
height: chartHeight,
chartArea: {
height: chartAreaHeight,
top: "100",
right: "100",
bottom: "100",
left: "100"
}
};
var chart = new google.visualization.BarChart(document.getElementById("chart"));
chart.draw(data, options);
};
window.onresize = function (event) {
chart.draw(data, options);
};
Now, I want to display annotations beside the bars displaying the value of that bar. How do I do that?
Here is the JSFiddle
to add annotations, add a column for the annotation text, directly after the column with the values.
in the following example, a DataView is used to add a calculated column for the annotations.
also, the resize function needs to be included in the same scope as the chart.
in the fiddle provided, an error will occur when the window is resized,
as the chart, data, and options variables are not available.
see following, working example...
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:B");
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
var data = response.getDataTable();
var chartAreaHeight = data.getNumberOfRows() * 10;
var chartHeight = chartAreaHeight + 70;
var options = {
// add text style for annotation
annotations: {
textStyle: {
fontSize: 8
}
},
title: "Andaman & Nicobar Islands",
legend: "none",
vAxis: {
title: "Year",
format: "0"
},
hAxis: {
title: "Rainfall (in mm)"
},
height: chartHeight,
chartArea: {
height: chartAreaHeight,
top: "100",
right: "100",
bottom: "100",
left: "100"
}
};
// format data for annotation
var formatter = new google.visualization.NumberFormat({pattern: '#,##0.0'});
formatter.format(data, 1);
// use view to add annotation column
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}]);
var chart = new google.visualization.BarChart(document.getElementById("chart"));
chart.draw(view, options);
window.addEventListener('resize', function () {
chart.draw(view, options);
}, false);
}
html,
body {
width: 100%;
height: 100%;
}
#chart {
width: 100%;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>
I initially had a columnchart on page1 and a linechart on page2. They both display fine when on their own page. When I try combine the two on one page, they both display but they both are columncharts. I'm not sure what I am doing wrong. This is my code so far:
google.load('visualization', '1.0', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawchart);
function drawchart() {
var chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Arm');
chartData.addColumn('number', 'Weight');
for (var i = 0; i < chartdatax.length; i++) {
chartData.addRow([parseFloat(chartdatax[i]),
parseFloat(chartdatay[i])]);
};
var options = {
height: 500,
hAxis: {
title: 'Arm C.G',
gridlines: {
count: 10
}
},
vAxis: {
title: 'Weight',
gridlines: {
count: 10
}
},
chartArea: {top:40, width: "70%", height: "75%"},
animation:{
duration: 1000,
easing: 'out',
startup: true,
},
legend: { position: 'none' },
pointSize: 5
};
myLineChart = new google.visualization.LineChart(document.getElementById('chart1'));
myLineChart.draw(chartData, options);
}
function drawchart2(elevations, status) {
var chartDiv = document.getElementById('elevation_chart');
if (status !== google.maps.ElevationStatus.OK) {
// Show the error code inside the chartDiv.
chartDiv.innerHTML = 'Cannot show elevation: request failed because ' +
status;
return;
}
var chart = new google.visualization.ColumnChart(chartDiv);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Sample');
data.addColumn('number', 'Elevation');
for (var i = 0; i < elevations.length; i++) {
data.addRow(['', elevations[i].elevation]);
}
chart.draw(data, {
height: 200,
legend: 'none',
titleY: 'Elevation (m)'
});
}
The code you have looks like it should work...
Would need to see where drawchart2 is called, the HTML elements, and any other code to be sure...
In this example, I add callback function drawcharts to start drawing...
google.load('visualization', '1.0', {'packages':['corechart'], 'callback': drawcharts});
function drawcharts() {
drawchart();
drawchart2();
}
function drawchart() {
var chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Arm');
chartData.addColumn('number', 'Weight');
for (var i = 0; i < 10; i++) {
chartData.addRow([
parseFloat(i),
parseFloat(i * 1.5)
]);
};
var options = {
height: 500,
hAxis: {
title: 'Arm C.G',
gridlines: {
count: 10
}
},
vAxis: {
title: 'Weight',
gridlines: {
count: 10
}
},
chartArea: {top:40, width: "70%", height: "75%"},
animation:{
duration: 1000,
easing: 'out',
startup: true,
},
legend: {position: 'none'},
pointSize: 5
};
myLineChart = new google.visualization.LineChart(document.getElementById('chart1'));
myLineChart.draw(chartData, options);
}
function drawchart2(elevations, status) {
var chartDiv = document.getElementById('elevation_chart');
var chart = new google.visualization.ColumnChart(chartDiv);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Sample');
data.addColumn('number', 'Elevation');
for (var i = 0; i < 10; i++) {
data.addRow([
'',
i * 100
]);
}
chart.draw(data, {
height: 200,
legend: 'none',
titleY: 'Elevation (m)'
});
}
<script src="https://www.google.com/jsapi"></script>
<div id="chart1"></div>
<div id="elevation_chart"></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);
}