So I have a Google Motion chart that displays data over time. A PHP is calling to a database to get data for the chart, that data is store into a JS file, and then the html file draws the chart (using a js script).
I want there to be a user input:
Start (millions):<input class="option" type="text" id="start" name="start" value="<?php echo $start?>"></input> |
End (millions): <input class="option" type="text" id="end" name="end" value="<?php echo $end?>"></input> |
where the user input will set the x values of the charts (which is in millions)
HTML and JS SCRIPT THAT DRAWS THE GRAPH:
function dataLoaded(myData) {
};
google.load('visualization', '1', {'packages':['motionchart']});
google.setOnLoadCallback(drawChart);
var control = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'options': {
// Filter by the date axis.
'filterColumnIndex': 0,
'ui': {
'chartType': 'MotionChart',
'chartOptions': {
'chartArea': {'width': '90%'},
},
}
},
});
function drawChart() {
// alert("dataLoaded called");
var chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Moving Avg Volume');
chartData.addRows(chartDataRows);
var upOptions = {};
upOptions['state'] = {"playDuration":15000,"orderedByY":false,"iconType":"VBAR","yAxisOption":"6","nonSelectedAlpha":0.4,"yZoomedDataMin":0,"showTrails":false,"yZoomedDataMax":2.2,"xAxisOption":"6","iconKeySettings":[],"duration":{"multiplier":1,"timeUnit":"D"},"xZoomedDataMin":0,"yLambda":1,"yZoomedIn":false,"uniColorForNonSelected":false,"xZoomedIn":false,"dimensions":{"iconDimensions":["dim0"]},"orderedByX":true,"sizeOption":"_UNISIZE","xZoomedDataMax":122,"xLambda":1,"colorOption":"4"};
upOptions['width'] = 900;
upOptions['height'] = 600;
var upchart = new google.visualization.MotionChart(document.getElementById('who_up_chart'));
upchart.draw(chartData, upOptions);
var downOptions = {};
downOptions['state'] = {"playDuration":15000,"orderedByY":false,"iconType":"VBAR","yAxisOption":"5","nonSelectedAlpha":0.4,"yZoomedDataMin":0,"showTrails":false,"yZoomedDataMax":24000,"xAxisOption":"5","iconKeySettings":[],"duration":{"multiplier":1,"timeUnit":"D"},"xZoomedDataMin":0,"yLambda":1,"yZoomedIn":false,"uniColorForNonSelected":false,"showXScalePicker":true,"xZoomedIn":false,"dimensions":{"iconDimensions":["dim0"]},"orderedByX":true,"showYMetricPicker":true,"sizeOption":"_UNISIZE","xZoomedDataMax":122,"xLambda":1,"colorOption":"4"};
downOptions['width'] = 900;
downOptions['height'] = 600;
var downchart = new google.visualization.MotionChart(document.getElementById('who_down_chart'));
downchart.draw(chartData, downOptions);
document.getElementById('loading').innerHTML='';
}
My X axis is from 0 to 100,000,000, and so if the user enters in 1,000,000 to 5,000,000 I want the chart to redraw and show only those points.
I think what you're looking for is a DataView. A DataView is like an interface for changing how you view the data in a DataTable without actually changing the data.
var data = new google.visualization.DataTable();
var options = {
//set your options
}
//Load Your Data Here.
var view = new google.visualization.DataView(data);
view.setRows(view.getFilteredRows([{column: 0, minValue: minTime, maxValue: maxTime}]);
var chart = new google.visualization.MotionChart(document.getElementById('chart_div'));
chart.draw(view, options)
I also noticed that you declare a ChartRangeFilter control at the beginning. To bind that to a chart the both need to be part of a google.visulization.Dashboard. I was unable to determine if a MotionChart is capable of binding with a control, but you could give it a try and find out.
Related
I'm mapping out ratings against episodes on a scatterplot on Google Charts. I have properly set the code up to send
data = [1, 8.7],[2, 8.8],[3, 8.3],[4, 8.4],[5, 9.3],[6, 8.9],[8, 9.3],[9, 8.4],[10, 8.3],[11, 8.4],[12, 8.9],[13, 8.7],[14, 9.2],[15, 9.1],[16, 8.6],[17, 8.9],[18, 9.3],[19, 9.3],[21, 8.7],[22, 8.5],[23, 8.3],[24, 8.7],[25, 9.3],[26, 9.6],[27, 8.8],[28, 8.5],[29, 7.8],[30, 8.5],[31, 9.5],[32, 9.7],[34, 8.3],[35, 8.1],[36, 8.7],[37, 8.7],[38, 8.5],[39, 8.9],[40, 9.3],[41, 8.9],[42, 9.6]
From Python to my graph.
Python:
def SendtoHTML():
dataPoint = data
return render_template('Scatter.html', series = series,finalEpNum = finalEpNum,minRatingFinal = minRatingFinal ,dataPoint = dataPoint)
if __name__ == '__main__':
app.run()
Script:
<script>
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var series = '{{series}}';
var finalEpNum = '{{finalEpNum}}'
var minRatingFinal = '{{minRatingFinal}}'
var data1 = google.visualization.arrayToDataTable([
['Episode', 'Rating'],
]);
var options = {
title: series,
hAxis: {title: 'Episode', minValue: 1, maxValue: finalEpNum},
vAxis: {title: 'Rating', minValue: minRatingFinal , maxValue: 10},
legend: true
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data1, options);
}
Which currently creates a google charts graph with all blue points.
However, I want to change colors of the datapoints after a given [x] value until another given [x] value. Kinda like this graph I made in matplotlib where the colors change from blue to red after season 1 ends. How would I achieve this in python or JS?
you can use a style column role
in your JS, add the role as the last column heading.
(the style role should follow the series column it represents)
var data1 = google.visualization.arrayToDataTable([
['Episode', 'Rating', {role: 'style', type: 'string'}], // <-- add style role
]);
then in your data, you can add the color each point should be...
data = [1, 8.7, 'blue'],[2, 8.8, 'blue'],[3, 8.3, 'blue'],[4, 8.4, 'red'],[5, 9.3, 'red'],[6, 8.9, 'orange'],[8, 9.3, 'orange'],[9, 8.4, 'orange'],
Here is my working code now after properly formatting the data block.
Python
def SendtoHTML():
finalEpNumParsable = int(finalEpNum)
datapointTest = [[1, 8.7, "0000ff"],[2, 6.7, "orange"],[3, 8.7, "0000ff"],[4,6.7,'red']]
render = render_template('Scatter.html', dataPoint = datapointTest)
return render
JS
function drawChart() {
var dataPoint = {{ dataPoint | tojson }};
var series = '{{series}}';
var finalEpUnparsed = {{finalEpNum}}
var finalEpNum = parseInt(finalEpUnparsed, 10);
var minRatingFinal = '{{minRatingFinal}}'
var data1 = google.visualization.arrayToDataTable([
['Episode', 'Rating', { role: 'style', type: 'string' }], // <-- add style role
dataPoint[0]
]);
for (i = 1; i < finalEpNum-5; i++){
data1.addRows([dataPoint[i]]);}
I am trying to develop report for my organization for that I am using google charts I am using bar chart for my report.
Is is the java script code I am using to display chart if I hard code values in google.visualization.DataTable(); the bar chart renders properly. If I try to fetch values from java script object it shows error.enter image description here
The java script code i am using is
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
var obj = JSON.parse('<?php echo json_encode($enroled_course) ?>');
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMaterial);
function drawMaterial() {
// alert(obj.toSource());
var data = new google.visualization.DataTable();
data.addColumn('string', 'Course Name');
data.addColumn('number', 'Completion Percentage');
data.addRows(20);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
var course_percent=val.id;
var course_name=val.fullname;
data.setCell(course_name,course_percent);
//console.log(val);
}
}
/*var data = new google.visualization.DataTable();
// Declare columns
data.addColumn('string', 'Employee Name');
data.addColumn('datetime', 'Hire Date');
// Add data.
data.addRows([
['Mike', {v:new Date(2008,1,28), f:'February 28, 2008'}], // Example of specifying actual and formatted values.
['Bob', new Date(2007,5,1)], // More typically this would be done using a
['Alice', new Date(2006,7,16)], // formatter.
['Frank', new Date(2007,11,28)],
['Floyd', new Date(2005,3,13)],
['Fritz', new Date(2011,6,1)]
]);*/
var materialOptions = {
chart: {
title: 'Enrolled courses Details'
},
hAxis: {
title: 'Completion Percentage',
minValue: 0
},
vAxis: {
title: 'Courses'
},
bars: 'vertical'
};
var materialChart = new google.charts.Bar(document.getElementById('chart_div'));
materialChart.draw(data, materialOptions);
}
</script>
<div id="chart_div"></div>
<div class="container">
<div class="row rounded">
<div class="col-sm border">
One of three columns
</div>
<div class="col-sm">
One of three columns
</div>
</div>
</div>
I will be very grateful if someone could say why I am getting invalid row index error while I am trying to insert a string in data.setCell(); method. I saw similar error but couldn't find the reason.
data table method setCell takes the following arguments...
setCell(rowIndex, columnIndex, value);
you're trying to pass row values, which is causing the error...
data.setCell(course_name,course_percent);
instead, don't add the rows initially, (remove --> data.addRows(20);)
add them once you have the values...
see following snippet...
var data = new google.visualization.DataTable();
data.addColumn('string', 'Course Name');
data.addColumn('number', 'Completion Percentage');
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
var course_percent=val.id;
var course_name=val.fullname;
data.addRow([course_name,course_percent]);
}
}
How does one combine a customized input range with the google charts pie chart to create an interactive graph?
The goal is for the Pie chart to display different percentages based on the position of the "input range."
var PercentageDeterminedBySlider would be a percent variable that changes based on the sliders position 1 through 5. The pie chart would then display this percentage.
code for pie chart
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChartPie);
function drawChartPie() {
var profitVar2 = PercentageDeterminedBySlider;
var other= 100-profitVar2;
var data3 = google.visualization.arrayToDataTable([
['Name', 'Profit Percentage'],
['Your Profit Percentage' , profitVar2],
['Potential for Growth', other]
]);
var options3 = {
title: 'Profit Percentage',
legend: 'none',
is3D: true,
pieSliceText: 'value',
};
var chart3 = new google.visualization.PieChart(document.getElementById('chart_divPie'));
chart3.draw(data3, options3);
}
code for input Range
<label for="points">Rating:</label>
<input type="text" id="textInput" value="5">
<input type="range" name="points" id="points" value="5" min="1" max="5" onchange="updateTextInput(this.value);">
Click below to see example
Example Image
Lastly, there is a slider(aka input range) integrated with Google charts on the Google website, however its' functionality appears to be very limited. So the goal here is to create a custom slider.
If I understand you correctly, there are some problems in your code. Here is some:
You can get the var PercentageDeterminedBySlider using document.querySelector('#points').value.
When the input change you can call again the method drawChartPie. It will take the updated value from the range.
Pay attention that you need to use praseInt to convert the range's value to int so the chart will work.
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChartPie);
function drawChartPie() {
var profitVar2 = parseInt(document.querySelector('#points').value);
var other = 100 - profitVar2;
var data3 = google.visualization.arrayToDataTable([
['Name', 'Profit Percentage'],
['Your Profit Percentage' , profitVar2],
['Potential for Growth', other]
]);
var options3 = {
title: 'Profit Percentage',
legend: 'none',
is3D: true,
pieSliceText: 'value',
};
var chart3 = new google.visualization.PieChart(document.getElementById('chart_divPie'));
chart3.draw(data3, options3);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<label for="points">Rating:</label>
<input type="text" id="textInput" value="5">
<input type="range" name="points" id="points" value="5" min="1" max="5" onchange="drawChartPie()">
<div id="chart_divPie"></div>
Click
http://output.jsbin.com/fawehez
Im trying to create a Google stacked bar chart with time on the y-axis and date on x - axis, with no success.
Ex: for 2012-05-01 i want a bar that goes from 00:00 to 24:00.
I have been able to create a simple stacked bar chart like this.
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Year', 'Austria', 'Bulgaria', 'Denmark', 'Greece'],
['2003', 1336060, 400361, 1001582, 997974],
['2004', 1538156, 366849, 1119450, 941795],
['2005', 1576579, 440514, 993360, 930593],
['2006', 1600652, 434552, 1004163, 897127],
['2007', 1968113, 393032, 979198, 1080887],
['2008', 1901067, 517206, 916965, 1056036]
]);
// Create and draw the visualization.
new google.visualization.BarChart(document.getElementById('visualization')).
draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
vAxis: {title: "Year"},
hAxis: {title: "Cups"},
isStacked: true}
);
}
What i'm trying to accomplish is something like this
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('string', 'Name');
data.addColumn('timeofday','Starttime');
data.addColumn('timeofday','Endtime');
data.addRows{
['2015-01-01','Funtime',[13,0,0],[16,0,0],
['2015-01-01','Boringtime',[16,0,0],[19,0,0],
['2015-01-02','Sleeptime',[1,0,0],[5,0,0],
}
The result of this would be two bars. At 2015-01-01 with two events one starting from 13:00 to 16:00 (in the y-axis) and on top of that another from 16:00 to 19:00. On 2015-01-02 there would also be one event from 1:00 to 5:00.
Am I able to do this with Google Bar charts?
Appreciate any help I can get.
there are a few problems in your code, you can check the browser's console for these errors
1.
the addRows method takes an array [] of rows,
and should be called with parenthesis () not curly braces {}
within the array, there should be another array for each row
the rows from the example are not complete and are missing the final bracket ]
['2015-01-01','Funtime',[13,0,0],[16,0,0],
should be
['2015-01-01','Funtime',[13,0,0],[16,0,0]],
2.
the data format does not allow a string column, after the first column
'Funtime' will have to go...
3.
if using type 'date' for the first column, then need actual date objects in the data
if --> data.addColumn('date', 'Date');
use --> [new Date('01/01/2016'), [13,0,0], [3,0,0]],
or a 'string' column can be used for the first column as well
if --> data.addColumn('string', 'Date');
use --> ['2015-01-01', [13,0,0], [3,0,0]],
4.
notice the date format used in this example --> '01/01/2016'
using '2016-01-01' with actual dates will result in problems such as these...
Google Charts Table displaying incorrect date
How do I align date and values to gridlines in Google Chart?
5.
finally, if you want time on the y-axis and date on x - axis
use ColumnChart instead of BarChart
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('timeofday','Starttime');
data.addColumn('timeofday','Endtime');
data.addRows([
[new Date('01/01/2016'), [13,0,0], [3,0,0]],
[new Date('01/02/2016'), [16,0,0], [3,0,0]],
[new Date('01/03/2016'), [1,0,0], [4,0,0]]
]);
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data, {
height: 600,
isStacked: true,
vAxis: {
format: 'HH:mm',
viewWindow: {
min: [0,0,0],
max: [24,0,0]
}
}
});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="visualization"></div>
I have a piechart showing the result the total bandwidth of uplink/downlink.
Right now, they suffix is GB.
I struggling trying to display their suffix different.
Example,
Downlink in GB
Uplink in KB.
I have
<script>
google.setOnLoadCallback(drawChart);
function drawChart() {
console.log(color['downlink']);
var data = google.visualization.arrayToDataTable([
['Task', 'Bandwith'],
['Downlink', ({{$t_down_bytes}})],
['Uplink', ({{$t_up_bytes}})]
]);
var options = {
legend: 'buttom',
pieSliceText: 'value', // text | none
title: 'Total Bandwith Usage',
colors: [color['downlink'], color['uplink']],
width:'100%',
height: 400,
slices: {
1: {offset: 0.1}
},
};
var formatter = new google.visualization.NumberFormat({
fractionDigits:2,
suffix: ' GB'
});
formatter.format(data, 1);
var chart = new google.visualization.PieChart(document.getElementById('private'));
chart.draw(data, options);
}
</script>
I can someone can shed some light on this.
Any hints / suggestions on this will be much appreciated !
One way is just doing it yourself: (Correct way to convert size in bytes to KB, MB, GB in Javascript might help)
var data = google.visualization.arrayToDataTable([
['Task', 'Bandwith'],
['Downlink', {v:6.4672328, f:"6.46 GB"}],
['Uplink', {v:9.40213213, f:"9.40 KB"}]
]);
Note that v is the "real" value google uses to draw and f is the formatted value it will show
If you want to keep your google formatter, another way is to add this line after your formatter.format(data, 1);
data.setFormattedValue(1,1,data.getFormattedValue(1,1).replace("GB","KB"))
Which sets the formattedValue of row 1, column 1
Update taking into account you want to use a mix of both:
var data = google.visualization.arrayToDataTable([
['Task', 'Bandwith'],
['Downlink', $t_down_bytes],
['Uplink', $t_up_bytes],
]);
var formatter = new google.visualization.NumberFormat({
fractionDigits:2
});
formatter.format(data, 1);
data.setFormattedValue(0,1,data.getFormattedValue(0,1) + ' {{$t_down_bytes_suffix}}')
data.setFormattedValue(1,1,data.getFormattedValue(1,1) + ' {{$t_up_bytes_suffix}}')
For more info on setFormattedValue and getFormattedValue check
Google Datatable Documentation