Paging google charts stacked column chart - javascript

I searched quite a bit for this, but haven't found what I'm looking for.
I'm building a stacked column chart using google charts, and I have over 200 rows. I want to page the results, but I haven't been able to accomplish it. Is it possible to page rows with a stacked column chart ? Here's my current code:
google.load('visualization', '1', {'callback':'drawChart', 'packages':['corechart']});
function drawChart() {
var jsonData = $.ajax({
type: 'GET',
url: "dashboard/lead/by-month",
dataType:"json",
async: false
}).responseText;
var data = new google.visualization.DataTable(
jsonData
);
var options = {
width: 900,
height: 400,
legend: { position: 'top', maxLines: 3 },
bar: { groupWidth: '75%' },
isStacked: true,
showRowNumber: true,
page: 'enable',
pageSize: 10,
sortColumn: 3,
sortAscending: false
};
var chart = new google.visualization.ColumnChart(document.getElementById("chartContainer"));
chart.draw(data, options);
};

You can do with external paging like, first you fetch 10 records from database and load the chart, after that same way you can call another 10 records with paging and load chart and so on.
The idea is to load chart with every call you make for to fetch records.

Related

Why doesn't my Google chart work on Safari?

I am trying to draw a chart on screen using Google charts. It works on every browser except for Safari. The following is the code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the bar chart package.
google.charts.load("current", {"packages":["corechart", "line"]});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
url: "/get-data-for-chart",
data: {"objectId": 807},
dataType: "json"
}).then(function(response) {
// Create our data table out of JSON data loaded from server.
rawData = response;
if (rawData.rows != null) rawData.rows = rawData.rows.map(row => ({ c: [{ v: new Date(row.c[0].v) }, row.c[1]] }));
var data = new google.visualization.DataTable(rawData);
// Instantiate and draw our chart, passing in some options.
var options = {
chart: {
title: "Title of the chart"
},
width: 900,
height: 500,
hAxis: {
title: "Time Axis",
format: "MM-dd",
gridlines: {count: 15}
},
vAxis: {
gridlines: {color: "none"},
minValue: 0,
format: "currency"
}
};
var date_formatter = new google.visualization.DateFormat({
pattern: "MMM dd, yyyy HH:mm"
});
date_formatter.format(data, 0);
var chart = new google.visualization.LineChart(document.getElementById("chart_div"));
chart.draw(data, options);
});
}
</script>
<!--Div that will hold the chart-->
<div id="chart_div"></div>
What actually happens on Safari is that the area for the chart loads, but with incorrect labels I guess. And the actual chart does not load at all. Moreover, there are no errors shown in the console, so I can't debug this in a usual way. As mentioned earlier, this works with all other browsers. Also for the record, the Safari is running on MacOS Mojave. Any help is greatly appreciated! Thanks.

How can I limit my Google chart to 7 items?

I'm wondering how I could limit the MAX amount of items it can display to my chart to 5. I've got a cron job updating the .json daily, and currently it just tries to fit them all onto there.
This is my code:
<script>
google.charts.load("visualization", "1", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "/server/database.json",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'Players Hourly',
'is3D':true,
legend: 'bottom',
hAxis: {
minValue: 0,
format: 'long'
},
vAxis: {
minValue: 0,
scaleType: 'log',
format: 'long'
},
pointSize: 5,
series: {
0: { pointShape: 'circle' },
}
};
var chart = new google.visualization.LineChart(document.getElementById('serverstats'));
chart.draw(data, options);
}
$(window).resize(function(){
drawChart();
});
</script>
Thank you.
an easy way would be to use a data view and the setRows method.
then use the view to draw the chart.
var data = new google.visualization.DataTable(jsonData);
var view = new google.visualization.DataView(data);
view.setRows([0, 1, 2, 3, 4]); //<-- provide an array of the row indexes you want to see
...
chart.draw(view, options); //<-- use view here
EDIT
to show the last 5 rows...
var viewRows = [];
for (var i = data.getNumberOfRows() - 1; i > data.getNumberOfRows() - 6; i--) {
viewRows.push(i);
}
view.setRows(viewRows);

Google Visualization stacked bar chart: colors and labels for each value

I'm using Google Visulaization API to render a chart showing a single row with multiple values, like this:
with the following code:
var data = google.visualization.arrayToDataTable([
['', '0%', '25%', '50%', '75%', '100%', {role: 'annotation'}],
['Mood', 3, 7, 20, 25, 45, '']
]);
var options = {
isStacked: true,
hAxis: { minValue: 0 }
}
var chart = new google.visualization.BarChart(document.getElementById('mood_chart'));
chart.draw(data, options);
Now I would like to customize the colors and add a label to every piece of the row.
If I do this:
var data = google.visualization.arrayToDataTable([
['', '0%', '25%', '50%', '75%', '100%', {role: 'annotation'}, {role: 'style'}],
['Mood', 3, 7, 20, 25, 45, 'ABC', '#f50']
]);
Then this only applies to the last value: (note the legend has also the wrong color)
And if I put an array of strings instead of a single label an error is given.
Is it possible to do what I am trying to do? How?
I have an interactive demo for this answer here.
The simple answer is that the annotation and style columns of the data table apply to the data column before them. Add annotation columns after each data column to add annotations to each value.
This is also why your colors differ from your legend. To apply colors to a series you do that from your options object. The style role of the data table affects an individual value without changing the option for the whole series.
var data = google.visualization.arrayToDataTable([
['', '0%', {role: 'annotation'}, '25%', {role: 'annotation'},
'50%', {role: 'annotation'}, '75%', {role: 'annotation'},
'100%', {role: 'annotation'}],
['Mood', 3, 'ABC', 7, 'DEF', 20, 'GHI', 25, 'JKL', 25, 'MNO']
]);
For assigning colors manually your options will look something like this:
var options = {
isStacked: true,
hAxis: {
minValue: 0
},
series: {
0:{color:'#222'},
1:{color:'#555'},
2:{color:'#888'},
3:{color:'#AAA'},
4:{color:'#EEE'}
}
};
My colors were just random greys because I can calculate the colors in my head that way. The series index is independant of the data table column, so it just assigns indexes to columns with data values.
In case someone would like to add the color series from json, i found a way to do that. It took quite some time to figure it out for me so here goes if anyone can use it.
Problem is that arrays of colors cannot be of type Array but must be object with objects.
Fetching colors from Controller (ASP.Net MVC):
/*array for colors to be convertet later*/
var mycolors = new Array();
function getColors() {
var postData = {};
postData.Ids = {1,2,3};
$.ajax({
type: "POST",
url: "#Url.Action("GoogleStackedBarchartColors", "MyController")",
data: postData,
dataType: "text",
success: function (d, status, request) {
/*some logging*/
console.log(d);
console.log($.parseJSON(d));
var colors = $.parseJSON(d);
/*I change the Type to object*/
mycolors.__proto__ = Object; /*The magic part*/
var i = 0;
colors.forEach(function (element) {
mycolors[i] = element;
i = i + 1;
});
And then in properties of the chart
var options = {
width: '100%',
height: 500,
bar: { groupWidth: '75%' },
bars: 'vertical',
legend: { 'position': 'top', maxLines: 3 },
isStacked: 'true',
series: mycolors /*Here we have the object containing colors*/
};

Google Line Chart Customization

I have these line charts here with real time data from an arduino.
What i want to do is to make the first graph (Temperature) better looking. I want to have always some gaps from the top and bottom (Like humidity) and i want to increase the width of the Y Axis of temperature. Is this possible ?
Both charts has run with exactly the same settings:
function drawTemperature() {
$.ajax({
url: 'http://192.168.1.3/Charts/chart_temperature.php',
dataType: 'json',
success: function (jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {
'title': 'Temperature',
'width': 1200,
'height': 600
//'legend.alignment' : 'start',
//'hAxis.baseline' : 5,
//'chartArea.top' : 20,
//'chartArea.left' : 500
//'focusTarget' : 'category'
//'animation.easing' : 'inAndOut'
//colors:['blue','#004411'],
//'hAxis.maxValue' : 30,
//'hAxis.showTextEvery' : 0.1,
//'hAxis.logScale' : 'true',
//'hAxis.gridlines.color' : '#00CC00',
//'hAxis.maxAlternation' : 10,
//'hAxis.viewWindow.max' : 10
//'curveType': 'function'
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_temperature'));
chart.draw(data, options);
}
});
}
function drawHumidity() {
$.ajax({
url: 'http://192.168.1.3/Charts/chart_humidity.php',
dataType: 'json',
success: function (jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_humidity'));
chart.draw(data, {width: 1200, height: 600});
}
});
}
function drawVisualization() {
drawTemperature();
drawHumidity();
}
You can create "gaps" at the top and bottom of you chart by setting the vAxis.minValue and vAxis.maxValue options to values less than the minimum and maximum (respectively) of your chart's data. Here's one way you might do this:
var range = data.getColumnRange(1);
var options = {
title: 'Temperature',
width: 1200,
height: 600,
vAxis: {
minValue: range.min - 1,
maxValue: range.max + 1
}
};

how to add table in the legend section of the highcharts

I need to be able to add a table right below the chart (possible in the legend section). I have a cpu chart but I need to be able to show if the threshold was breached and when.
Possibly in legend section, I need to be able call another series data (this is diffent that the chart data) and create table out of it.
This is what I have to create the cpu charts:
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false });
//$(function() {
function db_cpu() {
var timeout;
$.getJSON('db_cpu.php', function(data) {
// Create a timer
// Create the chart
$('#db_cpu_div').highcharts('StockChart', {
chart: {
borderColor: '#98AFC7',
borderRadius: 20,
borderWidth: 1,
events: {
load: function(chart) {
this.setTitle(null, {
});
}
},
zoomType: 'x'
},
exporting: {
enabled: true
},
legend: {
enabled: true
},
});
});
timeout = setTimeout(db_cpu, 300000);
}
db_cpu();
});
Is it possible to create another function in the legend section to make another json call to a php file to get another series and dispaly this data in table format?
Table will be something like this:
Threshold Breached (as the title)
Date Value
6/27/2013 12:00:00 96
6/29/2013 03:00:00 90
7/01/2013 09:00:00 75
7/05/2013 13:00:00 80
I need this area to be expandable/retractable with a + and - signs

Categories