Customized Interactive Input Range with Google Charts (Pie Chart) - javascript

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

Related

Create a Stacked Column Chart with series in javascript

I am trying to create a stacked column chart with 2 categories "Kosten" & "Stromertrag". Every category has it's own column with different values. Below is the attachment of what I want to achieve.
I tried to implement 4-5 chart libraries like canvasjs, highchart, etc. But they want the array of data. But in my case I have below json from which I want to build the same.
{
substratkosten: "9,000"
kosten1: "156,600"
kosten2: "298,286"
kosten3: "64,800"
strom2: "583,200"
substrat: "108,000"
}
Where first four values is for 'Kosten' category and last 2 values is for 'Stromertrag' category. I also tried to change the chart columns color, but I didn't found any property to achieve the same.
Can anyone please help to achieve the same?
Thanks in advance.
You can parse data in the format accepted by CanvasJS and render the chart. Below is the working code.
var jsonData = {
substratkosten: "9,000",
kosten1: "156,600",
kosten2: "298,286",
kosten3: "64,800",
strom2: "583,200",
substrat: "108,000"
};
var data = [];
for (var key in jsonData) {
if(key.includes("kosten")){
data.push({type: "stackedColumn", indexLabel: "{y}", dataPoints: [{x: 1, label: "Kosten", y: parseFloat(jsonData[key].replace(/,/g, ''))}]});
}
else {
data.push({type: "stackedColumn", indexLabel: "{y}", dataPoints: [{x: 2, label: "Stromertrag", y: parseFloat(jsonData[key].replace(/,/g, ''))}]})
}
}
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "StackedColumn Chart"
},
data: data
});
chart.render();
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>

Sending list information for google charts properly via flask to JS?

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]]);}

Show different suffix in Google Piechart

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

Changing series visibility of multiple dygraphs charts

UPDATED 7-10-15
I'm trying to control the visibility of data series across multiple plots using a set of check boxes. I have looked at a couple of the examples using the visibility option on the dygraphs website and other questions here but what I have found so far either focuses on a single chart or is limited in the details I need.
My first thought was to have the check boxes change the visibility values and then re-draw the charts, however I quickly realized that the visibility just reverts back to the initial conditions I set when creating the charts.
Now I'm wondering if I can create a function using the 'setVisibility' within its own loop to change the visibility of each chart as desired. Below is what I have recently tried, however it is not working. I'm not sure if this is the right way to accomplish this or not.
function change(el) {
for (i=0; i<23; i++) {
chart[i].setVisibility(el.id, el.checked);
}
}
My HTML code for check boxes:
<input type=checkbox id="0" checked onClick="change(this)"> <label for="0"> data1</label>
<input type=checkbox id="1" checked onClick="change(this)"> <label for="1"> data2</label>
<input type=checkbox id="2" checked onClick="change(this)"> <label for="2"> data3</label>
JS code to create plots:
var chart = [];
for (i=0; i<23; i++){
chart.push(
new Dygraph(
document.getElementById("div"+i),
csv[i],{
rollPeriod: 1, errorBars: true,
colors: ['#006600', '#993300', '#003399'],
title: name, connectSeparatedPoints: true,
drawPoints: true, sigFigs: 4, legend: 'always',
labelsSeparateLines: true, labelsDivWidth: 250,
visibility: [true, true, true]
}
)
);
}
I don't have much Javascript experience so I apologize if this is a simple problem, but it has been giving me fits.
I was able to find a solution to my problem. The issue was primarily rooted in the scope of my 'chart' variable, as it needed to be a global variable, which was not evident in my original post. By moving it outside of the containing function which fixed that issue.
<input type=checkbox id="acheck" index=0 checked onClick="change('acheck',0)"> <label for="0"> data1</label>
<input type=checkbox id="bcheck" index=1 checked onClick="change('bcheck',1)"> <label for="1"> data2</label>
<input type=checkbox id="ccheck" index=2 checked onClick="change('ccheck',2)"> <label for="2"> data3</label>
and the Javascript code I used:
for (i=0; i<23; i++) {
chart[i] = new Dygraph(
document.getElementById("div"+i), csv[i], {
rollPeriod: 1,
errorBars: true,
colors: ['#006600', '#993300', '#003399'],
connectSeparatedPoints: true,
drawPoints: true,
sigFigs: 4,
legend: 'always',
labelsSeparateLines: true,
labelsDivWidth: 250,
animatedZooms: false,
visibility: [vis2[0], vis2[1], vis2[2]],
}
);
}
function change(element,ind) {
var x=document.getElementById(element);
for (i=0; i<=22; i++) {
chart[i].setVisibility(ind, x.checked);
}
}

Redraw google after user input

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.

Categories

Resources