Render part of a large data set - dragToPan - javascript

I have 20000+ data points of the format [Date, Number], actual data is per hour for the last load of months.
I would like to show only the latest 28 days in the chart, but use the chart option explorer.actions: ['dragToPan', 'rightClickToReset'] to view data older than 28 days.
Basically, i want to show a subset of the data and then scroll to older data.
Is this even possible? Can someone provide an example of how its done?
google.charts.load('current', {
callback: function () {
var element = document.getElementById('#chart');
var data = google.visualization.arrayToDataTable([["Date","hits"],["2017-07-01",30],["2017-07-02",20],["2017-07-03",16],["2017-07-4",10],["2017-07-5",31],["2017-07-6",20],["2017-07-7",2],["2017-07-8",8],["2017-07-09",30],["2017-07-10",20],["2017-07-11",16],["2017-07-12",10],["2017-07-13",31],["2017-07-14",20],["2017-07-15",2],["2017-07-16",8]]);
var chart = new google.visualization.AreaChart(element);
var options = {
width: "100%",
height: "100%",
fontSize: 13,
animation: { duration: 1250, easing: 'out' },
legend: 'none',
chartArea: {
left: 40,
height: "80%",
width: "85%"
},
explorer: {
actions: ['dragToPan', 'rightClickToReset'],
axis: 'horizontal',
keepInBounds: false
},
hAxis: {
showTextEvery: 2,
textPosition: 'out',
format: 'dd MMM yy',
}
};
chart.draw(data, options);
},
packages:['corechart']
});

You can use hAxis.viewWindow.max and hAxis.viewWindow.max as per: https://developers.google.com/chart/interactive/docs/gallery/linechart
See: https://jsfiddle.net/5h7jxqq8/169/

Related

Pass dynamic variables in options to Google Charts

I am trying to pass a Series number in a Google Chart option through a variable. However it is not accepting it as a variable and instead is taking it as a string. You can see in Image1 that I have passed in Series parameter SecondseriesColumnNumber as a variable and value is 1.
Image 1
However in the output it is considering it as a string but not as the series number as shown below
Image 2
Other parameters are considering the values correctly but not the series one. How can I make this work? My code is below
var options = {
title: title,
width: width,
height: height,
bar: { groupWidth: '75%' },
chartArea: { left: "8%", right: "8%", top: "10%", width: "100%", height: "75%" },
backgroundColor: 'transparent',
tooltip: { textStyle: { color: 'black' }, isHtml: true },
isStacked: isStacked,
seriesType: seriesType,
series: { SecondseriesColumnNumber: { type: SecondseriesType } },
hAxis: { slantedText: true }
};
var chart = new google.visualization.ComboChart($('DivSeries')[0]);
the problem has to do with JavaScript syntax.
you are not able to use a variable as a key in the definition of an object.
you must first create the object, then you can add additional keys using variables.
there are two ways to get / set values of object keys, once the object is defined.
both of the following will return the same value for title.
var title = options.title;
var title = options['title'];
where as in the latter, we can substitute a variable for the title key.
var key = 'title';
var title = options[key];
in this case, define the static options as needed.
var options = {
title: title,
width: width,
height: height,
bar: { groupWidth: '75%' },
chartArea: { left: "8%", right: "8%", top: "10%", width: "100%", height: "75%" },
backgroundColor: 'transparent',
tooltip: { textStyle: { color: 'black' }, isHtml: true },
isStacked: isStacked,
seriesType: seriesType,
series: {},
hAxis: { slantedText: true }
};
then you can use a variable to further define the series option.
var SecondseriesColumnNumber = 1;
options.series[SecondseriesColumnNumber] = { type: SecondseriesType };

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>

Highcharts Solid Gauge Dynamic Update Using JSON

Updated & Resolved, see below.
I have been working on this for several days, searching and reading many tutorials and I am still stuck. Ultimately I am working on a page that will contain multiple solid gauge charts with data supplied by JSON from an SQLITE3 database. The database is updated every minute and I would like to have the chart data update dynamically, not by refreshing the browser page.
For the purpose of my learning, I have reduced this down to one chart.
All current and future data will be arranged as such:
PHP
[{"name":"s1_id","data":[684172]},
{"name":"s1_time","data":[1483097398000]},
{"name":"s1_probe_id","data":["28-0000071cba01"]},
{"name":"s1_temp_c","data":[22.125]},
{"name":"s1_temp_f","data":[71.825]},
{"name":"s2_id","data":[684171]},
{"name":"s2_time","data":[1483097397000]},
{"name":"s2_probe_id","data":["28-0000071d7153"]},
{"name":"s2_temp_c","data":[22.062]},
{"name":"s2_temp_f","data":[71.7116]}]
This is the current layout of my java:
JS
$(function() {
var options = {
chart: {
type: 'solidgauge'
},
title: null,
pane: {
center: ['50%', '90%'],
size: '140%',
startAngle: -90,
endAngle: 90,
background: {
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
innerRadius: '60%',
outerRadius: '100%',
shape: 'arc'
}
},
tooltip: {
enabled: false
},
// the value axis
yAxis: {
stops: [
[0.10, '#2b908f'],//Blue
[0.35, '#55BF3B'],//Green
[0.65, '#DDDF0D'],//Yellow
[0.90, '#DF5353']//Red
],
lineWidth: 0,
minorTickInterval: null,
tickPixelInterval: 1000,
tickWidth: 0,
title: {
y: -70
},
labels: {
y: 16
},
min: 0,
max: 1000000,
title: {
text: 'Degree C'
}
},
plotOptions: {
solidgauge: {
dataLabels: {
y: -10,
borderWidth: 0,
useHTML: true
}
}
},
series: []
};
var gauge1;
$.getJSON('sgt3.php', function(json){
options.chart.renderTo = 'chart1';
options.series.push(json[0]);
gauge1 = new Highcharts.Chart(options);
});
});
I was using information from this post but it leaves off the dynamic update aspect. As I mentioned before, I will have more charts rendering to div ids, all coming from the one JSON array, which is why I have referenced the following link:
Multiple dynamic Highcharts on one page with json
If anyone has an idea how to dynamically update this please let me know. I have tried several setInterval methods but all they seem to do is redraw the chart but no data is updated.
Update:
I spent a while doing some more iterations and resolved before coming back here. I changed each gauge to have their own function such as:
$('#gauge0').highcharts(Highcharts.merge(options, {
yAxis: {
min: 15,
max: 30,
tickPositions: [15, 20, 25, 30],
title: {
text: 'Table'
}
},
credits: {
enabled: false
},
series: [{
data: [30],
dataLabels: {
y: 20,
format: '<div style="text-align:center"><span style="font-size:48px;color:' +
((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y:.3f}</span><br/>' +
'<span style="font-size:12px;color:silver">Degree C</span></div>'
},
tooltip: {
valueSuffix: 'Tooltip 1'
}
}]
}));
Then got the setInterval to work by assigning to each gauge respectively. I have added a lot more info than just the two I referenced but each var and setData can be added respectively.
// Bring life to the dials
setInterval(function() {
$.ajax({
url: 'data_temps.php',
success: function(json) {
var chart0 = $('#gauge0').highcharts();
var chart1 = $('#gauge1').highcharts();
// add the point
chart0.series[0].setData(json[3]['data'],true);
chart1.series[0].setData(json[8]['data'],true);
},
cache: false
})
}, 1000)
Hopefully this can help someone in the future. This may not be the most efficient way but its working great right now. Thanks again everyone for your suggestions.
You may try something like this:
change:
var gauge1;
$.getJSON('sgt3.php', function(json){
options.chart.renderTo = 'chart1';
options.series.push(json[0]);
gauge1 = new Highcharts.Chart(options);
});
to:
options.chart.renderTo = 'chart1';
var gauge1 = new Highcharts.Chart(options);
$.getJSON('sgt3.php', function(json){
gauge1.series[0].points.length = 0;
gauge1.series[0].points.push(json[0]);
});
That is, updating the existing series on a chart instead of re-creating it.
As I've mentioned in the comment before, highcharts provide an example of dynamically updated gauge:
http://jsfiddle.net/gh/get/jquery/3.1.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/gauge-solid/

GoogleChart not drawing properly

My Chart has a datetime value and two number values (positive and negative).
The above image shows the results of drawing one bar, datetime being current date, the problem is, the bar covers 1990 to 2050, when it should only be covering the current month.
If I draw 2 bars, one for last month, and one for current month, everything is drawn properly.
I'm assuming GoogleCharts needs at least 2 dates for some reason. Does anyone have any idea how to fix this, or give some direction.
Thanks in advance,
Edit to ADD:
The Chart that I am using:
google.charts.load('current', {packages: ['corechart', 'controls']});
The single bar that I am drawing comes from this data store in historyChart:
[["2016-10-01T00:00:00+00:00", 5000.0, 0]]
I am inserting this data to the chart in this manner:
data.addColumn('datetime', 'Chart Filter');
data.addColumn('number');
data.addColumn('number');
data.addRows(historyChart);
The Chart wrapper and options are as followed:
var programmaticChart = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'programmatic_chart_div',
'options': {
displayExactValues:false,
vAxis: {
format: '$#,###', //add $sign in virtical axis
viewWindowMode: 'maximized',
},
hAxis:{
format: 'MMM-yyyy',
},
width: 900,
height: 450,
chartArea: {
'backgroundColor': {
'fill': '#F4F4F4',
'opacity': 100
},
top:50,
left:85,
width: 1000
},
title: "{{ member.username }}'s chart", //set user name as chart's title
isStacked:"true",
bar:{groupWidth: "95%"},
colors: ['#7FFF00', '#e6693e'],
}
});
// Create and draw the visualization.
dashboard.bind(programmaticSlider, programmaticChart);
dashboard.draw(data);
adding option for hAxis.ticks seems to help...
see following working snippet...
google.charts.load('43', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Chart Filter');
data.addColumn('number');
data.addColumn('number');
data.addRows([
[new Date("10/01/2016"), 5000.0, 0]
]);
var programmaticChart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'programmatic_chart_div',
dataTable: data,
options: {
displayExactValues: false,
vAxis: {
format: '$#,###',
viewWindowMode: 'maximized'
},
hAxis:{
format: 'MMM-yyyy',
ticks: [new Date("10/01/2016")]
},
width: 900,
height: 450,
chartArea: {
backgroundColor: {
fill: '#f4f4f4',
opacity: 100
},
top: 50,
left: 85,
width: 1000
},
title: '{{ member.username }}\'s chart',
isStacked: 'true',
bar:{groupWidth: '95%'},
colors: ['#7fff00', '#e6693e']
}
});
programmaticChart.draw();
//dashboard.bind(programmaticSlider, programmaticChart);
//dashboard.draw(data);
},
packages: ['corechart', 'controls']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="programmatic_chart_div"></div>

Dojo chart won't display after addSeries

I am trying to create a chart in dojo. The issue is, as soon as I try and add any data to the chart, the chart renders blank (no errors).
Code:
var cPosition
require(["dojox/charting/Chart","dojox/charting/themes/Claro", "dojox/charting/plot2d/Grid", "dojox/charting/axis2d/Default", "dojox/charting/plot2d/MarkersOnly",], function(Chart, theme, Grid, Default, MarkersOnly){
cPosition = new Chart("chartPosition");
cPosition.setTheme(theme);
cPosition.addAxis("x", {
min: -180,
max: 180,
majorTicks: true,
majorTick: {length:180},
minorTick:{length:5},
majorTickStep:180,
minorTickStep:20
});
cPosition.addAxis("y", {
min: -180,
max: 180,
vertical: true,
majorTicks: true,
majorTick: {length:180},
minorTick: {length:5},
majorTickStep:180,
minorTickStep:20
});
cPosition.addPlot("Grid", { type: Grid,
hMajorLines: true,
hMinorLines: true,
vMajorLines: true,
vMinorLines: true,
majorHLine: { color: "black", width: 2 },
majorVLine: { color: "black", width: 2 },
minorHLine: { color: "grey", width: 1 },
minorVLine: { color: "grey", width: 1 },
enableCache: true });
cPosition.addPlot("default", { type: MarkersOnly });
//cPosition.addSeries("series_markers", [{x:10,y:10}]);
cPosition.render();
});
If I uncomment the line:
cPosition.addSeries("series_markers", [{x:10,y:10}]);
The chart turns blank (absolutely nothing on it). If I comment the line, the grid displays correctly but, of course, no data.
What I am trying to accomplish is create an x,y grid that will display a marker that corresponds to the position of an object.

Categories

Resources