I was wondering how can I make linear function in javascript like if you search on google:
y=2x+7
I tried using google charts but it didnt work...
here is the code:
google.charts.load('current', {
packages: ['corechart', 'line']
});
google.charts.setOnLoadCallback(drawCurveTypes);
var x = 0;
var y = 0;
var h = window.prompt('enter a number');
function drawCurveTypes() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'linear');
data.addRows([
]);
for (var i = 0; i <= 5; i++) {
addRows('[x,y]');
x = x + h;
y++;
}
var options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Popularity'
},
series: {
1: {
curveType: 'function'
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Thanks!
Related
So I have this chart:
google.charts.load('44', {
callback: drawAxisTickColors,
packages: ['controls', 'corechart']
});
function drawAxisTickColors() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'value');
var dateArr2 = (<?php echo json_encode($dateArr); ?>);
console.log(dateArr2);
var bitcoinArr = (<?php echo json_encode($numbers); ?>);
console.log(bitcoinArr);
bitcoinArr = bitcoinArr.map(Number);
var array = [];
var length = Math.min(dateArr2.length, bitcoinArr.length);
for (var i = 0; i < length; ++i) {
array.push([ new Date(dateArr2[i]), bitcoinArr[i] ]);
}
data.addRows(array);
var control = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'control_div',
options: {
filterColumnIndex: 0,
ui: {
chartOptions: {
height: 50,
width: 600,
chartArea: {
width: '80%'
}
}
}
}
});
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chart_div',
options: {
width: 620,
chartArea: {
width: '80%'
},
hAxis: {
format: 'hh:ss',
slantedText: false,
maxAlternation: 1
}
}
});
function setOptions() {
var firstDate;
var lastDate;
var v = control.getState();
if (v.range) {
document.getElementById('dbgchart').innerHTML = v.range.start + ' to ' + v.range.end;
firstDate = new Date(v.range.start.getTime() + 1);
lastDate = new Date(v.range.end.getTime() - 1);
data.setValue(v.range.start.getMonth(), 0, firstDate);
data.setValue(v.range.end.getMonth(), 0, lastDate);
} else {
firstDate = data.getValue(0, 0);
lastDate = data.getValue(data.getNumberOfRows() - 1, 0);
}
var ticks = [];
for (var i = firstDate.getMonth(); i <= lastDate.getMonth(); i++) {
ticks.push(data.getValue(i, 0));
}
chart.setOption('hAxis.ticks', ticks);
chart.setOption('hAxis.viewWindow.min', firstDate);
chart.setOption('hAxis.viewWindow.max', lastDate);
if (dash) {
chart.draw();
}
}
setOptions();
google.visualization.events.addListener(control, 'statechange', setOptions);
var dash = new google.visualization.Dashboard(document.getElementById('dashboard'));
dash.bind([control], [chart]);
dash.draw(data);
}
I use this chart to show import per user, but every time I draw the chart this happens:
As you can see the chart keeps it's old data, this slows down my website. I tried clearChart() but my chart ingores it's or give's an error:
clearchart is not a function
I also tried this:
Google Chart Constant Redrawing Memory Increase
but this doesn't seem to work for me.
What am I doing wrong?
Please help.
I solved it
don't call the google api a 100 times
My Google Sheet Data Looks like this
I am trying to create a Dashboard with 2 Tables and a Line chart based on my data.
I managed to create a single table and Line chart earlier obtained from same data range, but I am having difficulties creating 2 different tables whose data source is from the same google sheet but different cell range.
Here is my Code.
Code 1
function doGet(e) {
return HtmlService
.createTemplateFromFile("Line Chart multiple Table")
.evaluate()
.setTitle("Google Spreadsheet Chart")
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getSpreadsheetData() {
var ssID = "1qkDFf4sYMgPZhGAoEf7vrXbBPmno6Tt4UT_zd5M8xLo";
var sheet = SpreadsheetApp.openById(ssID).getSheets()[0];
var data1 = sheet.getDataRange({A6: F16}).getValues();
var data2 = sheet.getDataRange({A1: F4}).getValues();
var rows = {data1: data1,data2: data2};
return rows;
}
Code 2
<!DOCTYPE html>
<html>
<head>
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="line"></div>
<div id="table1"></div>
<div id="table2"></div>
<script>
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(getSpreadsheetData);
function getSpreadsheetData() {
google.script.run.withSuccessHandler(drawChart).getSpreadsheetData();
}
function drawChart(rows) {
var data1 = google.visualization.arrayToDataTable(rows.data1, false);
var data2 = google.visualization.arrayToDataTable(rows.data2, false);
var options = {
title: 'SPC Chart',
legend: 'none',
chartArea: {
width: '60%'
},
vAxis: {
textStyle: {
fontFamily: 'Arial',
fontSize: 12
}
}
};
var chart = new google.visualization.LineChart(document.getElementById("line"));
chart.draw(data1, options);
var table1 = new google.visualization.Table(document.getElementById("table1"));
table1.draw(data1, {showRowNumber: true, width: '50%', height: '100%'});
var table2 = new google.visualization.Table(document.getElementById("table2"));
table2.draw(data2, {showRowNumber: false, width: '50%', height: '100%'});
}
</script>
</body>
</html>
I am quite new and unsure on how to proceed.
The following code helped me to achieve what i wanted.
Code 1
function doGet(e) {
return HtmlService
.createTemplateFromFile("Line Chart multiple Table")
.evaluate()
.setTitle("Google Spreadsheet Chart")
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getSpreadsheetData() {
var ssID = "1qkDFf4sYMgPZhGAoEf7vrXbBPmno6Tt4UT_zd5M8xLo";
var sheet = SpreadsheetApp.openById(ssID).getSheets()[0];
var data2 = sheet.getRange('A1:F5').getValues();
var firstrow = 6; // 6th row
var range = sheet.getRange(firstrow, 1, sheet.getLastRow() - firstrow + 1, 6);
var data1 = range.getValues();
//var data1 = sheet.getRange('A6:F15').getValues();
rows = {data1: data1, data2: data2};
return rows;
Code 2
<!DOCTYPE html>
<html>
<head>
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="line"></div>
<div id="table1"></div>
<div id="table2"></div>
<script>
google.charts.load('current', {'packages':['table']});
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(getSpreadsheetData);
function getSpreadsheetData() {
google.script.run.withSuccessHandler(drawChart).getSpreadsheetData();
}
function drawChart(rows) {
var data2 = google.visualization.arrayToDataTable(rows.data2, false);
var data1 = google.visualization.arrayToDataTable(rows.data1, false);
var options = {
title: 'SPC Chart',
legend: 'none',
chartArea: {
width: '60%'
},
vAxis: {
textStyle: {
fontFamily: 'Arial',
fontSize: 12
}
}
};
var table2 = new google.visualization.Table(document.getElementById("table2"));
table2.draw(data2, {showRowNumber: false, width: '50%', height: '100%'});
var chart = new google.visualization.LineChart(document.getElementById("line"));
chart.draw(data1, options);
var table1 = new google.visualization.Table(document.getElementById("table1"));
table1.draw(data1, {showRowNumber: true, width: '50%', height: '100%'});
}
</script>
</body>
</html>
I have a Google line chart which doesn't show up after loading the page. After the first resize everything works.
How can I get the chart show up after loading the page?
Data comes from locale text file on the server. This textfile holds the date/time and a sensor value. Textfile gets split and used as data for the chart.
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart () {
$.ajax({
url: 'Temp.ESP',
type: 'get',
success: function (txt) {
var dataArray = [['Name', 'Date']];
var txtArray = txt.split('\n');
for (var i = 0; i < txtArray.length; i++) {
var tmpData = txtArray[i].split(/\s+/);
dataArray.push([tmpData[0], parseInt(tmpData[1])]);
}
var data = google.visualization.arrayToDataTable(dataArray);
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
var options = {width: '100%',
height: '40%',
legend: 'none',
colors: ['red'],
hAxis: {
textStyle:{color: 'white'}},
vAxis: {
textStyle:{color: 'white'}},
backgroundColor: { fill:'transparent' }};
$(window).resize(function(){
chart.draw(data,options);
});
}
});
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
setInterval(function(){
$.get( "mydata.php", function( data ) {
$( "#mydata" ).html( data ); // this will replace the html refreshing its content using ajax
});
}, 1000);
/* Chart */
#chart{
width: 100%;
}
<div id="chart">
<div id="chart_div"></div>
</div>
thank you!
Hard to know what's going on without being able to run your code, but it could just be a simple css fix. Try changing the parent to a flex container at 100vw and the child chart at flex:1
#chart{
width: 100vw;
display: flex;
// adjust the padding accordingly
}
#chart_div {
flex: 1;
}
I forgot to call the draw function.
First call was in the resize function.
function drawChart () {
$.ajax({
url: 'Temp.ESP',
type: 'get',
success: function (txt) {
var dataArray = [['Name', 'Date']];
var txtArray = txt.split('\n');
for (var i = 0; i < txtArray.length; i++) {
var tmpData = txtArray[i].split(/\s+/);
dataArray.push([tmpData[0], parseInt(tmpData[1])]);
}
var data = google.visualization.arrayToDataTable(dataArray);
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
var options = {width: '100%',
height: '40%',
legend: 'none',
colors: ['red'],
hAxis: {
textStyle:{color: 'white'}},
vAxis: {
textStyle:{color: 'white'}},
backgroundColor: { fill:'transparent' }};
chart.draw(data,options); //forgot this call
$(window).resize(function(){
chart.draw(data,options);
});
}
});
Thanks for the inspiration!
This code creates a scatterplot with an image of a pie chart on it.
I'm having a problem making the data row entry to be shown in the axis of the Scatterplot.
Any idea in how to make that happen?
Many thanks :)
google.charts.load('current', {'packages':['corechart']});
function draw0hedgeChart() { var data = new google.visualization.DataTable(); data.addColumn('number', 'X'); data.addColumn('number', 'Y');
data.addRows([ [ 9.87, 6.53], ]);
var options = {
colors: ['#000000'],
legend: 'none',
title: 'Risk vs. Return with 0% Hedge Fund',
hAxis: {title: 'Risk', minValue: 3, maxValue: 11, gridlineColor: '#fff', direction: -1},
vAxis: {title: 'Return', minValue: 4, maxValue: 10, gridlineColor: '#fff'},
width:900,
height:500
};
var container = document.getElementById('chart0_div');
var chart = new google.visualization.ScatterChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var layout = chart.getChartLayoutInterface();
for (var i = 0; i < data.getNumberOfRows(); i++) {
var xPos = layout.getXLocation(data.getValue(i, 0));
var yPos = layout.getYLocation(data.getValue(i, 1));
var widget0 = container.appendChild(document.createElement('img'));
widget0.src = 'img/0.png';
widget0.className = 'chart0';
// (overlay the dot)
widget0.style.top = (yPos - 50) + 'px';
widget0.style.left = (xPos - 50) + 'px';
} });
chart.draw(data, options); }
i think you may be referring to the configuration options for...
{hAxis,vAxis,hAxes.*,vAxes.*}.ticks
hAxis.ticks - Replaces the automatically generated X-axis ticks with the specified array. Each element of the array should be either a valid tick value (such as a number, date, datetime, or timeofday)
e.g.
google.charts.load('current', {
callback: draw0hedgeChart,
packages: ['corechart']
});
function draw0hedgeChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Y');
data.addRows([
[9.87, 6.53],
]);
var ticksX = [];
var ticksY = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
ticksX.push(data.getValue(i, 0));
ticksY.push(data.getValue(i, 1));
}
var options = {
colors: ['#000000'],
legend: 'none',
title: 'Risk vs. Return with 0% Hedge Fund',
hAxis: {
title: 'Risk',
minValue: 3,
maxValue: 11,
//gridlineColor: '#fff',
direction: -1,
ticks: ticksX
},
vAxis: {
title: 'Return',
minValue: 4,
maxValue: 10,
//gridlineColor: '#fff',
ticks: ticksY
},
width:900,
height:500
};
var container = document.getElementById('chart0_div');
var chart = new google.visualization.ScatterChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var layout = chart.getChartLayoutInterface();
for (var i = 0; i < data.getNumberOfRows(); i++) {
var xPos = layout.getXLocation(data.getValue(i, 0));
var yPos = layout.getYLocation(data.getValue(i, 1));
var widget0 = container.appendChild(document.createElement('img'));
widget0.src = 'http://findicons.com/files/icons/512/star_wars/16/clone_old.png';
widget0.className = 'chart0';
// (overlay the dot)
widget0.style.position = 'absolute';
widget0.style.top = yPos + 'px';
widget0.style.left = xPos + 'px';
}
});
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart0_div"></div>
How can I set a legend and labels for my Google pie chart?
The deprecated method had this ability: https://developers.google.com/chart/image/docs/gallery/pie_charts
Also, how can I make it so that onclick the selected slice gets exploded from the pie a little?
Here's what I have so far:
<div id="pie_chart_div" style="width: 940px; height: 500px;"></div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(render_applicant_sources);
function render_applicant_sources() {
var data = new google.visualization.arrayToDataTable([["Source","Number of Applicants"],["Hospitality Online",222],["Indeed",22]]);
data.addColumn('string', 'Geocoder');
data.addColumn('number', 'Geocodes');
var chart = new google.visualization.PieChart(document.getElementById('pie_chart_div'));
var options = {
title: 'Scottsdale Resort & Conference Center from December 1, 2012 to December 1, 2013',
is3D: true,
colors: [ '#2483b3', '#AAC789', '#1E4147', '#437356', '#F34A53', '#FAE3B4' ],
titleTextStyle: { bold: false },
legend: { position: 'labeled' }
};
chart.draw(data, options);
google.visualization.events.addListener(chart, 'click', function(e){
var data = chart.getSelection();
if(data.length > 0) {
chart.setSelection([]);
}
});
}
</script>
http://jsfiddle.net/xHwZW/
You need to use a "select" event handler, and set the chart's slices.<slice index>.offset option:
google.visualization.events.addListener(chart, 'select', function() {
var selection = chart.getSelection();
if (selection.length > 0) {
if (!options.slices || !options.slices[selection[0].row]) {
// if this is the first time the user clicked on the pie,
// or if the user clicks on an unexploded slice,
// unexplode all slices and explode the selected slice
options.slices = [];
options.slices[selection[0].row] = {
offset: 0.4
};
}
else {
// otherwise the user clicked on an exploded slice, so unexplode all slices
options.slices = [];
}
chart.draw(data, options);
}
else {
options.slices = [];
chart.draw(data, options);
}
});
See working example: http://jsfiddle.net/asgallant/R8yAK/