How do I switch between two input files/arrays with Google Charts? - javascript

I'm including multiple plots with Google Charts. I'd like to display one chart at a time but allow the user to switch between multiple csv input files. A change in input data would also require a change in chart and axis titles. I'm new to Javascript and I'm not sure how best to do this.
Here's how I'm currently plotting one csv. Any tips on how to toggle the change in input file would be appreciated. I'm currently using the jquery-csv module to read in my csv file into an array.
Script created in header.
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// Reading in a locally stored CSV file to an array of numbers
$.get("2017T.csv", function(csvString) {
var dataarray = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// Turning array into format usable by Google Charts
var data = google.visualization.arrayToDataTable(dataarray);
// Formatting Google Charts
var options = {
title: 'Raspberry PI Temperature plot - Yearly',
titleTextStyle: {
fontSize: '18',
},
vAxis: {
title: 'Temperature (\u00B0 C)' ,
titleTextStyle: {
italic: 'FALSE',
fontSize: '14',
},
baseline: '0',
baselineColor: 'black',
gridlines: { color: 'transparent'},
},
hAxis: {
title: 'Date',
titleTextStyle: {
italic: 'FALSE',
fontSize: '14',
},
baseline: '0',
baselineColor: 'black',
gridlines: { color: 'transparent'},
},
curveType: 'function',
backgroundColor: {
stroke: 'black',
strokeWidth: '5',
},
haxis: {
title: 'Hello',
},
legend: {position: 'none'},
};
//Creating Charts
var chart = new google.visualization.LineChart(document.getElementById('temp_year'));
chart.draw(data, options);
});
}
Chart called in body.
<div id="temp_year" style="width: 800px; height: 400px"></div>

You can accomplish this by making your drawChart function generic and then passing in the chart specific data each time you draw. This allows you redraw with new data and even makes it so it'll handle dynamic data too.
For example, based on your code you might do something like:
var chartData = {};
var dataarray;
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(function () {
drawChart(chartData);
});
// Reading in a locally stored CSV file to an array of numbers
$.get("2017T.csv", function (csvString) {
dataarray = $.csv.toArrays(csvString, { onParseValue: $.csv.hooks.castToScalar });
});
// Turning array into format usable by Google Charts
var data = google.visualization.arrayToDataTable(dataarray);
chartData = {
title: 'Raspberry PI Temperature plot - Yearly',
data: data
}
function drawChart(chartData) {
// Formatting Google Charts
var options = {
title: chartData.title,
titleTextStyle: {
fontSize: '18',
},
vAxis: {
title: 'Temperature (\u00B0 C)',
titleTextStyle: {
italic: 'FALSE',
fontSize: '14',
},
baseline: '0',
baselineColor: 'black',
gridlines: { color: 'transparent' },
},
hAxis: {
title: 'Date',
titleTextStyle: {
italic: 'FALSE',
fontSize: '14',
},
baseline: '0',
baselineColor: 'black',
gridlines: { color: 'transparent' },
},
curveType: 'function',
backgroundColor: {
stroke: 'black',
strokeWidth: '5',
},
haxis: {
title: 'Hello',
},
legend: { position: 'none' },
};
//Creating Charts
var chart = new google.visualization.LineChart(document.getElementById('temp_year'));
chart.draw(chartData.data, options);
}
So what I've done is created a chartData object that you can define any chart specific variables in. I've only done the title and data, but obviously you can do as many of the chart options as you want. Then, when you want to redraw the chart, you overwrite the chartData object with the new chart's data and call drawChart again with the new data.

Related

Google Charts change color on side box

So I'm using Google Charts and using the Column charts (https://developers.google.com/chart/interactive/docs/gallery/columnchart) specifically and I have a question regarding colors on charts.
Here are two questions:
Does anyone know how to change the color on the outer box? I was able to change the color on the bars to the orange color, but I can't target the outer box.
I am using 'Aug', 7283, 'color: #ff8a73' to define the hex colors on each bar, does anyone know a better way to define colors or is this the proper way?
Here is the JS code:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(sle_interactions);
function sle_interactions() {
var data = google.visualization.arrayToDataTable([
['Year', 'Interactions', { role: 'style' }],
['Aug', 7283, 'color: #ff8a73'],
['Sep', 8263, 'color: #ff8a73'],
['Oct', 9827, 'color: #ff8a73'],
['Nov', 9362, 'color: #ff8a73'],
['Dec', 10625, 'color: #ff8a73']
]);
var options = {
title: 'Interactions',
is3D: true,
backgroundColor: 'transparent',
hAxis: {
title: 'Timeframe',
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('sle_interactions'));
chart.draw(data, options);
}
document.addEventListener('DOMContentLoaded', sle_interactions);
Both of the questions have been resolved using this:
var options = {
title: 'Age Range',
is3D: true,
backgroundColor: 'transparent',
hAxis: {
title: 'Followers',
},
vAxis: {
minValue: 0,
maxValue: 100,
format: "#.#'%'",
},
colors: ['#ff8a73'],
};

Google Line Chart - Unknown lines Issue

I am trying to generate a multicolor line chart refer jsfiddle code
The chart that's being generated by Google chart shows three straight lines (red, green and blue) which should not be part of the chart at all.
See attached image
When I am rendering the chart of individual colors, in that case, the chart is coming up fine but when I am combining them together, in that case, one can see these straight lines appearing out of nowhere.
Here's the code snippet, refer jsfiddle for the actual code
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawAxisTickColors);
function drawAxisTickColors() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Bets');
data.addColumn('number', 'Values');
data.addColumn({type:'string', role:'style'});
data.addRows([[5,100,"color:#D3D3D3"],[10,200,"color:#D3D3D3"],[15,300,"color:#D3D3D3"]]);
var options = {
height: 450,
title: 'Monte Carlo',
curveType: 'function',
legend: 'none',
backgroundColor: { fill:'transparent' },
intervals: { 'style': 'line' },
hAxis: {
title: 'Bets',
textStyle: {
color: '#33465C'
},
titleTextStyle: {
color: '#33465C'
}
},
vAxis: {
title: 'Results',
textStyle: {
color: '#33465C'
},
titleTextStyle: {
color: '#33465C'
}
},
titleTextStyle: {
color: '#33465C'
},
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Any guidance to resolve this will be much appreciated.

Not able to zoom in on Google Charts

I have created a Google Chart that visualises the outside temperature at my house. The amount of data keeps growing, so the chart gets unreadable in a few days ;-)
I want to be able to zoom in on the x-axis, but I can't get it to work with the explorer option.
I've tried:
explorer: { actions: ["dragToZoom", "rightClickToReset"],
maxZoomIn: 0.2,
maxZoomOut: 1.0,
zoomDelta: 10,
axis: "horizontal",
keepInBounds: true
},
But that doesn't seem to work.
Here's what I've got so far:
https://codepen.io/wtrdk/pen/wpGVVW or https://weather.wtrdk.nl/test.html
UPDATE:
I've added the following code to create a continuous axis, but I still can't zoom in...
var view = new google.visualization.DataView(data);
view.setColumns([
// first column is calculated
{
calc: function (dt, row) {
// convert string to date
return new Date(dt.getValue(row, 0));
},
label: data.getColumnLabel(0),
type: 'datetime'
},
// just use index # for second column
1
]);
try using the current library...
<script src="https://www.gstatic.com/charts/loader.js"></script>
jsapi is out of date, according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader.js from now on.
this will only change the load statement,
see following working snippet...
google.charts.load('current', {
packages: ['corechart', 'controls']
}).then(function () {
$.get(
"https://cors-anywhere.herokuapp.com/https://weather.wtrdk.nl/temperature.csv",
function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {
onParseValue: $.csv.hooks.castToScalar
});
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
var view = new google.visualization.DataView(data);
view.setColumns([
// first column is calculated
{
calc: function (dt, row) {
// convert string to date
return new Date(dt.getValue(row, 0));
},
label: data.getColumnLabel(0),
type: 'datetime'
},
// just use index # for second column
1
]);
var temperature = new google.visualization.ChartWrapper({
chartType: "AreaChart",
containerId: "temperature",
dataTable: view,
options: {
height: 400,
explorer: {
actions: ["dragToZoom", "rightClickToReset"],
//axis: "horizontal",
//keepInBounds: true
},
animation: { duration: 2000, easing: "out", startup: true },
title: "Temperature",
titleTextStyle: { color: "grey", fontSize: 11 },
legend: { textStyle: { color: "grey", fontSize: 11 } },
backgroundColor: { fill: "transparent" },
colors: ["#e39c3a"],
hAxis: {
textStyle: {
color: "grey",
fontSize: 11
},
//format: 'datetime',
},
vAxis: {
title: "°C",
titleTextStyle: {
color: "grey",
fontSize: 22
},
textStyle: {
color: "grey",
fontSize: 11
}
}
}
});
temperature.draw();
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://weather.wtrdk.nl/jquery.csv.min.js"></script>
<body bgcolor="#282B30">
<div id="temperature"></div>
</body>

Color bars in Google Chart by their value

I'm trying to color the bars in a Google Charts bar chart by their value. I know from the documentation that I can specify a style role to color specific bars a specific color, but I haven't been able to locate an example showing whether it's possible to color bars by their value.
I have created a fiddle demonstrating my chart structure. My data is a continuous series of integers.
var data = google.visualization.arrayToDataTable([
['Asset','Days in Stock'],
['4990/473',606],['4990/489',504],['4990/557',159],['4990/559',147],
['4990/578',87],['4990/581',63],['4990/582',53],['4990/586',41],
['4990/590',25],['4990/592',20],['4990/593',5],
]);
I haven't been able to determine from the documentation whether it's in fact possible to set threshold ranges for setting the bar colors. Ideally I'd want to be able to use a range formatter but it doesn't seem to work with the bar chart type.
var formatter = new google.visualization.TableColorFormat();
formatter.addRange(0, 60, 'green', '#00ff00');
formatter.format(data, 1);
https://jsfiddle.net/dL997yv6/
So if there is a way to do this using a format function that would be ideal, however if there isn't then I will settle for programmatically setting the color per bar using my data values in my scripting language.
the color formatter works on Table charts
to set the color of the bar by value, add a calculated column to the data view,
similar to the annotation column
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Asset','Days in Stock'],
['4990/473',606],['4990/489',504],['4990/557',159],['4990/559',147],
['4990/578',87],['4990/581',63],['4990/582',53],['4990/586',41],
['4990/590',25],['4990/592',20],['4990/593',5],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
// style column
{
calc: function (dt, row) {
if ((dt.getValue(row, 1) >= 0) && (dt.getValue(row, 1) <= 60)) {
return 'green';
} else if ((dt.getValue(row, 1) > 60) && (dt.getValue(row, 1) <= 100)) {
return 'yellow';
} else {
return 'red';
}
},
type: 'string',
role: 'style'
},
// annotation column
{
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}
]);
var options = {
title: '',
titleTextStyle: {
fontSize: 16,
bold: true
},
backgroundColor: 'transparent',
chartArea: {
left:80,
top:30,
bottom:60,
right:10
},
legend: {
textStyle: {
fontSize: 11
}
},
vAxis: {
title: 'Asset',
textStyle: {
fontName: 'Arial',
fontSize: 10
},
titleTextStyle: {
fontSize: 12,
italic: false,
bold:true
}
},
hAxis: {
title: 'Days in Stock',
gridlines: {
count: 22
},
textStyle: {
fontName: 'Arial',
fontSize: 11
},
titleTextStyle: {
fontSize: 12,
italic: false ,
bold:true
}
},
pointSize: 3,
pointShape: 'circle',
annotations: {
alwaysOutside: true,
textStyle: {
fontName: 'Arial',
fontSize: 9,
color: '#000000',
opacity: 1
}
}
};
var chartDiv = document.getElementById('chart_div');
var chart = new google.visualization.BarChart(chartDiv);
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

How to speed up google chart loading

I have this problem, I hope it is not too especific: I take some data from different servers (the amount of the servers would vary, but in my test case there are 10 servers besides my localhost) to create the charts. They work absolutely fine, but they are too slow for my taste (the column and bar chart take about 5 seconds while the geo chart takes around 10 seconds)
This is the ajax call used to get the data from the servers:
$.ajax({
url: [server's php page where i get i data'],
type: 'POST',
data: {
[some data]
},
success: function(data) {
(JSON.parse(data || "null") != null) ? [function for success case] : false;
},
error: function() {
[function for error case]
}
});
Code used to create the charts once I have all the needed data:
var options = {
title: title,
hAxis: {title: axis_title, titleTextStyle: {color: '#F0F0F0'}, baselineColor: '#F0F0F0', textStyle: {color: '#F0F0F0'}},
vAxis: {titleTextStyle: {color: '#F0F0F0'}, baselineColor: '#F0F0F0', textStyle: {color: '#F0F0F0'}},
legend: {textStyle: {color: '#F0F0F0'}},
titleTextStyle: {color: '#F0F0F0', fontName: 'Arial', fontSize: '13px', bold: false},
fontSize: 12,
backgroundColor: {fill: 'transparent'},
colors: ['#04c']
};
chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
Basically my question is this: are the charts generated slowly because of a google chart api/ajax/etc or is this caused by a mistake I'm doing?
Thanks!

Categories

Resources