I need to only show two rows on my Google Charts table. I currently have the following that is being called:
function drawTable() {
var jsonData = '#Html.Raw(ViewData["totalsTable"])';
var table;
var data;
var options;
data = new google.visualization.DataTable(jsonData);
table = new google.visualization.Table(document.getElementById('table_div'));
options = { 'pageSize': 2 };
table.draw(data, options);
}
The problem being that this is showing a table with all of the values from the DataTable. I just want to show the first two rows. options = { 'pageSize': 2 } is supposed to achieve this. I'm not sure what I'm doing wrong. Thanks!
Paging is disabled by default; you have to enable it by setting the page option to 'enable':
options = {
page: 'enable',
pageSize: 2
};
[Edit - instructions on how to display a specific set of rows only, without paging]
If you want to display a specific set of rows, you can use a DataView to restrict the rows displayed:
var view = new google.visualization.DataView(data);
// the #setRows method takes an array of row indices as an argument
// display the first two rows only (indices 0 and 1):
view.setRows([0, 1]);
// use the view to draw your table instead of the DataTable:
table.draw(view, options);
Incidentally, you don't have to put quotes around the output of #Html.Raw(ViewData["totalsTable"]) if it is valid JSON. Leaving them out is moderately more efficient, as the Visualization API won't have to convert your JSON into a javascript object:
var jsonData = #Html.Raw(ViewData["totalsTable"]);
For the 'pageSize' option to work, paging must be enabled.
options = { 'pageSize': 2 };
Based on your post, I think you need the setColumns method. Documentation here:
https://developers.google.com/chart/interactive/docs/reference?hl=ja#DataView_setColumns
Related
What i am trying to do is i want to display a chart based on my dynamic data i used Angular ForEach to loop through all my objects array see my code below:
var parse = JSON.parse(jsondata);
angular.forEach(parse, function (value, key) {
var dataSet = anychart.data.set(value);
var chart = anychart.column();
var series = chart.column(value);
chart.title("Data Sets: Array of Objects");
chart.container("container");
chart.draw();
});
it correctly display the count of my chart but the data of each object array is not showing up see picture below
but if put a static data like this :
var data = [
{x:"January", value: 12000},
{x:"February", value: 15000},
{x:"March", value: 16000},
{x:"April", value: 14000},
{x:"May", value: 10000}
];
the chart displays correctly.
can anyone help me with this ? any help will greatly appreciated.
Everything depends on the value content inside the loop. You are applying the value to the series and dataSet as well.
If you are using dataSet, you should apply the value to the dataSet, map the data, then apply the mapping to the series. Like this:
var dataSet = anychart.data.set(value);
var mapping = dataSet.mapAs({'x': 0, 'value': 1}); // for example
var chart = anychart.column();
var series = chart.column(dataSet);
The mapping depends on your data. If the value includes ready-to-use data that matches the default mapping you can apply it directly to the series.
Can you share the value content?
The chart can work with dynamic data. All you need is to apply new data to the existing dataSet, like this:
dataSet.data(newData);
And that's it! There's no need to recreate chart/series/dataSet.
I'm using numerous Google visualization Tables to display a variety of data in a single-paged, multi-tabbed web app. Some of these tables have columns that use formatted values. When a user clicks on the column header for these columns, the data is sorted according to the sort order of the underlying values rather than the sort order of the formatted values. This results in some cases in the data not appearing to the user to be sorted.
I'm looking for a way to fix this that can be reused across all my Tables, preferably by writing one event listener that can be attached to each Table and will handle all of the specifics regardless of the data types used in the various columns of the various associated DataTables, and regardless of whether any given column uses formatted values. I do have the condition that if any cell in a column uses a formatted value, then all of the cells in that column do, but I do not have the condition that every column uses formatted values. If a column does not use formatted values, then I want the normal sort based on the type of data in the column (e.g., number, string, date, etc.).
As an example, I could have a DataTable like the following. (This data is not actual data, but mirror situations that are problematic for me.)
var dataTable = new google.visualization.DataTable({
cols: [
{type: 'number', label: 'ID'},
{type: 'number', label: 'Places'},
{type: 'string', label: 'Things'}
],
rows: [
{c:[{v:1},{v:102735,f:'Harbor Place'},{v:'pet',f:'Dalmation'}]},
{c:[{v:2},{v:163848,f:'Alphaville'},{v:'my',f:'Top Favorites'}]},
{c:[{v:3},{v:113787,f:'Beta City'},{v:'ten',f:'Best Things'}]}
]
});
Without my doing any special configuration, this table, if sorted ascending on the ID column, would look like this, as the user would expect:
ID Places Things
----------------------------------
1 Harbor Place Dalmation
2 Alphaville Top Favorites
3 Beta City Best Things
If the user clicks on the header for the Places column, the table then looks like this, because the ascending sort is performed on the underlying numeric values:
ID Places Things
----------------------------------
1 Harbor Place Dalmation
3 Beta City Best Things
2 Alphaville Top Favorites
The user, however, expects the table to look like this:
ID Places Things
----------------------------------
2 Alphaville Top Favorites
3 Beta City Best Things
1 Harbor Place Dalmation
If the user clicks on the header for the Things column, the table would sort ascending as follows, because of the sort order of the underlying string values:
ID Places Things
----------------------------------
2 Alphaville Top Favorites
1 Harbor Place Dalmation
3 Beta City Best Things
The user is expecting this:
ID Places Things
----------------------------------
3 Beta City Best Things
1 Harbor Place Dalmation
2 Alphaville Top Favorites
I've searched on StackOverflow and on Google and haven't found any discussion of this particular situation. So I've been working on writing my own event listener, but it quickly became very involved when trying to write it as something that can be reused for any of my Tables. So am I missing something simple? Has anyone else had a situation like this and resolved it; if so, what did you do?
you can use the DataView Class to set the row order
dataView.setRows([1, 2, 0]);
then draw the chart with the DataView
table.draw(dataView, options);
getting the order of the rows during the 'sort' event is the tricky part,
since there aren't any convenience methods for formatted values, such as getDistinctValues
in the following working snippet, the formatted values are extracted into an array,
sorted, then getFilteredRows is used to get the row index of the formatted value
google.charts.load('current', {
callback: function () {
var dataTable = new google.visualization.DataTable({
cols: [
{type: 'number', label: 'ID'},
{type: 'number', label: 'Places'},
{type: 'string', label: 'Things'}
],
rows: [
{c:[{v:1},{v:102735,f:'Harbor Place'},{v:'pet',f:'Dalmation'}]},
{c:[{v:2},{v:163848,f:'Alphaville'},{v:'my',f:'Top Favorites'}]},
{c:[{v:3},{v:113787,f:'Beta City'},{v:'ten',f:'Best Things'}]}
]
});
// use DataView to set order of rows
var dataView = new google.visualization.DataView(dataTable);
dataView.setRows([1, 2, 0]);
var table = new google.visualization.Table(document.getElementById('chart_div'));
var options = {
// use event to set order
sort: 'event',
// set column arrow
sortColumn: 1,
sortAscending: true
};
google.visualization.events.addListener(table, 'sort', function(props) {
var sortValues = [];
var sortRows = [];
var sortDirection = (props.ascending) ? 1 : -1;
// load values into sortable array
for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
sortValues.push({
v: dataTable.getValue(i, props.column),
f: dataTable.getFormattedValue(i, props.column)
});
}
sortValues.sort(function (row1, row2) {
return row1.f.localeCompare(row2.f) * sortDirection;
});
// set row indexes
sortValues.forEach(function (sortValue) {
sortRows.push(dataTable.getFilteredRows([{column: props.column, value: sortValue.v}])[0]);
});
// use DataView to set order of rows
dataView.setRows(sortRows);
// set column arrow
options.sortColumn = props.column;
options.sortAscending = props.ascending;
table.draw(dataView, options);
});
table.draw(dataView, options);
},
packages: ['table']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Good morning. I'm working with Chart.js and have it set up to produce a nice bar chart. Unfortunately, the default popup when you hover over the bars only shows the color of the bar and it's value. The color of the bar is unhelpful to our users. I would like the popup to display the label of each bar in the group and its value. Sort of like:
First Project : 80
Second project : 25
Third project : 64
There have been other posts about this issue and they recommended using
multiTooltipTemplate : "<%%=datasetLabel%> : <%%=value%>"
I tried it but it had no effect. No errors but no change to the popup. Perhaps it isn't set up correctly. Any suggestions?
$.post(url, dataObject)
.done(function (results) {
if (results.length > 0) {
//Build mydatasets empty array
var mydatasets = [];
//Loop through the results and build a new data array object to be added to the master data array object that will
//be assigned to the chart bars.
for (var i = 0; i < results.length; i++) {
var dataset =
{
label : results[i].WorkTypeName,
fillColor : getRandomColor(), //Found in the ChartHelpers.js file
data : results[i].Hours
}
mydatasets.push(dataset);
}
//Plug the data into the data structure
var data = {
labels: startdates,
datasets: mydatasets
};
//Get chart context
var ctx = $("#myChart").get(0).getContext("2d");
// This will get the first returned node in the jQuery collection and use it to create a bar chart
myBarChart = new Chart(ctx, {
options: {
multiTooltipTemplate : "<%%=datasetLabel%> : <%%=value%>"
}
}).Bar(data);
}
});
Found the answer with some additional experimentation! Other forum posts had suggested using
multiTooltipTemplate : "<%%=datasetLabel%> : <%%=value%>"
in the options. that generated a syntax error message. Removing the extra two percent signs caused the popup to display as planned.
multiTooltipTemplate : "<%=datasetLabel%> : <%=value%>"
I have a template that uses jQuery/AJAX to pull some data. Getting the data isn't an issue, but I can't seem to use it in a way that GoogleVis wants. The line causing problems for me is mapdata.addRows([gapidata]);. It seems there's an issue with the array but I'm not sure how to fix it. Any help is greatly appreciated!
The jQuery/AJAX I'm using:
var gapidata = new Array();
$.ajax({
url: "inc/index.gapi.inc.php",
cache: false,
dataType: "text",
success: function(html){
gapidata = html;
}
});
The data I get from the AJAX call:
['Korea, Republic of', 50],['Japan', 38]
The code I use to display the data:
// Geo Map Chart
var mapWidth = Math.round(((screenWidth / 12) * 10) * 0.8);
var mapHeight = Math.round(mapWidth * 0.5);
$('#dashboard-visit-map').width(mapWidth*1.1);
$('#dashboard-visit-map').height(mapHeight*1.1);
var mapdata = new google.visualization.DataTable();
mapdata.addColumn('string','Country');
mapdata.addColumn('number','IPs Listed');
mapdata.addRows([gapidata]);
var geochart = new google.visualization.GeoChart(document.getElementById('dashboard-visit-map'));
geochart.draw(mapdata, {width: mapWidth, height: mapHeight,backgroundColor: { fill:'transparent' }});
Currently the map doesn't populate with any data. If I remove the brackets around gapidata I receive the following error on my JavaScript console:
Uncaught Error: Row given with size different than 2 (the number of columns in the table).
I just normalized my data frame before calling the rendering function; it worked fine for me.
Normalizes data frame:
data <- as.data.frame.matrix(data)
I had same problem.
the solution is.
re-initialize your chat visulization object mapdata for each ajax request;
i.e.
// before calling ajax
mapdata = null;
mapdata = new google.visualization.DataTable();
// ajax codeenter code here
I know that my answer may not be related to your code format, but it may help other people, as it is for the same issue. If you make an AJAX call to json data and then you loop over them, then you must be sure that you include all the columns of the JSON data in the addCollumn() method. If you don't want to include all of the data, then you should use the delete command in the for-loop like this:
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string','category');
dataTable.addColumn('string','context');
dataTable.addColumn('string','id');
dataTable.addColumn('number','location_subtype');
dataTable.addColumn('string','location_type');
dataTable.addColumn('string','month');
dataTable.addColumn('string','persistent_id');
var json=JSON.parse(jsonData);
for (var i=0;i<json.length;i++) {
//Deleted rows
delete json[i].location;
delete json[i].outcome_status;
var row = [];
for (var item in json[i]) {
row.push(json[i][item]);
}
dataTable.addRow(row);
}
If you don't delete them, then it is assumed that you need those data and the table takes an unexpected size by default. Therefore, you will encounter the error in the console. I hope that this may be helpful for some people. Cheers
I have a csv file that looks like that:
week,value1,value2
1,2,3
2,7,9
I would like to plot a stacked graph of it using google chart (week being my x (horizontal) values and values1 and values2 being the two set of y's). Unfortunately, I didn't find any easy way to do so. That probably relates to me being a complete noob in js.
Is there any simple way to do that?
The jquery-csv library provides the ability to translate a string of csv into an array to be used by google.visualization.arrayToDataTable() (their example here). To make this work, add jquery.csv.js to your server (in the example below I assume it is in the same folder as your HTML) and link to it in your <head>. The following is a simple script you can add to your <head> to get started. I assume a scatter chart, but this process works for any of the charts here. You will also need a <div> with id="chart" for this to work.
// load the visualization library from Google and set a listener
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
// this has to be a global function
function drawChart() {
// grab the CSV
$.get("example.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);
// this view can select a subset of the data at a time
var view = new google.visualization.DataView(data);
view.setColumns([0,1]);
// set chart options
var options = {
title: "A Chart from a CSV!",
hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
legend: 'none'
};
// create the chart object and draw it
var chart = new google.visualization.ScatterChart(document.getElementById('chart'));
chart.draw(view, options);
});
}
I have been searching for a while, and found the solution on a Google group discussion.
https://groups.google.com/forum/#!topic/google-visualization-api/cnXYDr411tQ
I have tried it, and it works!
In this case, we have to specify the header types of our csv file.
var queryOptions = {
csvColumns: ['number', 'number', 'number' /* Or whatever the columns in the CSV file are */],
csvHasHeader: true /* This should be false if your CSV file doesn't have a header */
}
/* csvUrl is the path to your csv */
var query = new google.visualization.Query(csvUrl, queryOptions);
query.send(handleQueryResponse);
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.ColumnChart(document.getElementById('your div'));
// Draw your chart with the data table here.
// chart.draw(view, queryOptions);
}
What server side scripting language are you working in (php, asp)?
One option could be to import the data from a spreadsheet saved in Google Drive, see here for a PHP based example of saving and extracting data from Google Docs. This would then enable you to update the spreadsheet and the chart would automatically plot the new data.