Not able to zoom in on Google Charts - javascript

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>

Related

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.

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

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.

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>

Highcharts multiple y axis with data from csv file

I've been creating charts on my company's website with data that is populated from a csv file. I need to add two additional y axes on the right side of the chart. I tried doing so by following Highchart's instructions, but my data is coming from a CSV file and I can't manage to get the two additional axes to connect to the data. Meaning, the other two splines look flat compared to the one that is actually plotting to it's y axis.
Below is the chart's JS file. The CSV file is 4 columns, which from left to right are Date, Overall, VIX, GSPC
Thank you in advance!
function basi_overall_chart() {
//var to catch any issues while getting data
var jqxhr_basi_overall = $.get('../../datafiles/basi/company_BASI_Overall_VIXSP.csv', function (data) {
var options = {
//chart options
chart: {
//set type of graph, where it renders
type: 'line',
renderTo: 'basi_overall_container'
},
//set title of graph
title: {
text: 'company Bid-Ask Spread Index (BASI)',
style: {
color: '#4D759E'
},
align: 'center'
},
//set xAxis title
xAxis: {
title: {
text: 'Date',
style: {
color: '#4D759E',
fontWeight: 'bold'
}
}
},
//set yAxis info
yAxis: [{
title: {
text: 'Basis Points (BPS)',
style: {
color: '#4D759E',
fontWeight: 'bold'
}
},
labels: {
//give y-axis labels commas for thousands place seperator
formatter: function () {
return Highcharts.numberFormat(this.value);
}
},
//set y-axis to the left side
opposite: false,
//set background grid line width
gridLineWidth: 1
}, { // Second yAxis
gridLineWidth: 1,
title: {
text: 'VIX',
style: {
color: '#de5a3c',
fontWeight: 'bold'
}
},
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value);
}
},
opposite: true
}, { // Third yAxis
gridLineWidth: 1,
title: {
text: 'SP',
style: {
color: '#4D759E',
fontWeight: 'bold'
}
},
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value);
}
},
opposite: true
}],
//stylize the tooltip
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>',
valueDecimals: 4
},
//enable and stylize the legend
legend: {
enabled: true,
layout: 'horizontal',
align: 'center',
borderWidth: 1,
borderRadius: 5,
itemDistance: 20,
reversed: false
},
//set the starting range. 0-5. 5="All", 4="1yr", etc
rangeSelector: {
selected: 5,
allButtonsEnabled: true
},
//set general plot options
plotOptions: {},
//disable credits
credits: {
enabled: false
},
//make download as csv format correctly
navigator: {
series: {
includeInCSVExport: false
}
},
//set name of chart downloads
exporting: {
filename: 'company_basi_overall',
//enable download icon
enabled: true,
//add image to download
chartOptions: {
chart: {
events: {
load: function () {
this.renderer.image('http://www.company.com/images/company_logo2.gif', 90, 75, 300, 48).attr({
opacity: 0.1
}).add();
}
}
},
//remove scrollbar and navigator from downloaded image
scrollbar: {
enabled: false
},
navigator:{
enabled: false
}
},
//make download as csv format correctly
csv: {
dateFormat: '%Y-%m-%d'
}
},
//set graph colors
colors: ['#002244', '#DBBB33', '#43C5F3', '#639741', '#357895'],
//series to be filled by data
series: []
};
//names of labels in order of series. make sure they are the same as series header in data file
var names = ['BASI', 'VIX', 'SP'];
//get csv file, multiply by 100 (divide by .01) and populate chart
readCSV(options, data, 1.0, names);
var chart = new Highcharts.StockChart(options);
})
//catch and display any errors
.fail(function (jqxhr_basi_overall, exception) {
ajaxError(jqxhr_basi_overall, exception, '#basi_overall_container');
});
}
(function () {
//set high level chart options for all charts
Highcharts.setOptions({
lang: {
thousandsSep: ','
}
});
$('.chart_container').toggle(false);
basi_overall_chart();
$('#basi_overall_container').toggle(true);
all_crossable_volume_chart();
auto_assign_toggle_chart_buttons();
})();

Highstock, Dynamically add Points, a definied time span at the beginning

I have the following issue:
I want to dynamically update a hightstock Chart with Points from Ajax Calls. For Example i use setInterval(addPoints,3000); How can i develope the code, that the highstock Charts display an definied time, e.g. 1 Minute, and the Chart beginn to draw from the Left without this "time poping and squeezing? For a testrun i tried to you predifned null points, but the interval is not fix.
var value1="valueNo1";
var value2="valueNo2";
var color1="green";
var color2="red";
$(function () {
$('#container').highcharts('StockChart',{
chart: {
type: 'spline',
zoomtype: 'z'
},
title: {
text: 'Live random data'
},
navigator: {
top: 500
},
legend: {
enabled: true
},
rangeSelector: {
buttons: [{
count: 30,
type: 'second',
text: '30s'
}, {
count: 1,
type: 'minute',
text: '1M'
}, {
count: 2,
type: 'minute',
text: '2M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 1
},
xAxis: {
type: 'datetime'
}
});
});
var chart = $('#container').highcharts();
var ct = (new Date()).getTime();
// addAxis
chart.addAxis({ labels: { format: '{value}' , style: {color: color1 } }, title: { text: value1 , style: {color: color1} } , lineColor: color1, lineWidth: 0, opposite:true } );
chart.addAxis({ labels: { format: '{value}', style: {color: color2 } }, title: { text: value2 , style: {color: color2} } , lineColor: color2, lineWidth: 0 } );
// addSeries
chart.addSeries({ "name": "value1","data": [], yAxis: 2, marker: {enabled:true, radius: 5 }});
// addPoint
var current_time = (new Date()).getTime();
chart.series[0].addPoint([current_time+64000, null], false);
addPoints = function(){
var current_time = (new Date()).getTime();
chart.series[0].addPoint([current_time, Math.random()*10], false);
chart.redraw();
}
setInterval(addPoints,3000);
Please see jsFiddle demo of the issue :
http://jsfiddle.net/ehonk/FLzRH/1/
Please help
The "popping" is the data being added and the line connecting the last point to the new point and the yAxis re-scaling. To minimize this I would set the yAxis.max to a value that is the maximum possible. Secondly I would look at the animation and see which kind you want to use when it adds a new point.
To handle the "sqeezing" you can set your "viewable" range and your adding of points such that when you add a new point the last point on the left falls out of the viewable area.
You can also call setExtremes to set range on the xAxis.

Categories

Resources