Data not showing up in Google Chart - javascript

I've looked at every thread I could find on how to get a json feed into my google chart, but nothing seems to be working or the threads are slightly different from my problem.
Update: I'm trying to parse my json feed to only show certain columns. For example, my feed has a Actual and Goal column. I want my chart to only show the Actual column. I need the goal column for filtering reasons on the back end, so when the feed updates from the database it knows which records to pull.
After carefully following the json format for Google charts and figuring out a way to add the data, i'm am still unsuccessful in getting the actual data to show up. What's weird is that the graph shows up, it just doesn't have any data in it. I get no errors in my console.I've made sure my json string is valid, it is. I've tried logging my json feed to make sure that the information is being passed correctly and it is. The columns are added, as in the code, but the rows just won't show up.
I believe that in my data.addRow line, i'm not traversing correctly, but can't seem to figure out how to correctly get down to the specific cell.
function drawChart() {
$.ajax({
url: "--",
dataType:"json",
success: function (result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Quarter');
data.addColumn('number', 'Actual');
for (var i = 0; i < result.rows.length; i++) {
data.addRow([result.rows[i], result.rows[i], result.rows[i]]);
}
Here is my json feed:
{ "cols":[ {"label":"Quarter", "type":"string"},{"label": "Actual", "type":"number"}, {"label":"Goal","type":"number"}], "rows":[ {"c":[{"v":"Q1"}, {"v":22}, {"v":30}]},
{"c":[{"v":"Q2"}, {"v":24}, {"v":30}]},
{"c":[{"v":"Q3"}, {"v":27}, {"v":30}]}
]}

You could build the DataTable with your raw JSON:
var data = new google.visualization.DataTable(json);
and then use a DataView to filter out your "Goal" column:
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
Draw your chart using the DataView instead of the DataTable:
chart.draw(view, options);

You can pass your response data from ajax call (as Json formated) to your DataTable
var data = new google.visualization.DataTable(responseData);

Related

Update stock price in anychart without re-plotting whole chart

I am playing with the Anychart stock candlestick chart which is very nice, in order to update the chart I use a setInterval function but it re-plots the entire chart which sucks because if I am zooming or something it resets and starts over obviously. Is there a way I can just update last price from the database every couple seconds without re-plotting the whole chart?
Current setInterval function to load chart:
setInterval(function() {
$.get('chart_data.php', function(data) {
$(".main_cont").replaceWith(data);
});
}, 2000);
My chart_data variable:
$chart_data .= "{'x':'".$open_time."','open': ".$open.",'high': ".$high.",'low': ".$low.",'close': ".$close."},";
chart_data.php file:
anychart.onDocumentReady(function() {
// create a data table
var table = anychart.data.table('x');
// add data
table.addData([<?php echo $chart_data;?>]);
// add data
//table.addData([ {'x':'08/09/2020 10:11','open': 11000,'high': 10000,'low': 8000,'close': 8500}]);
// create a stock chart
var chart = anychart.stock(true);
// create a mapping
var mapping = table.mapAs({
'date': 'date',
'open': 'open',
'high': 'high',
'low': 'low',
'close': 'close',
'fill': 'fill'
});
var plot = chart.plot(0);
// add a series using the mapping
chart.plot(0).candlestick(mapping).name();
// set container id for the chart
chart.container('container');
var series = chart.plot(0).candlestick(mapping);
chart.scroller().xAxis(false);
// initiate chart drawing
chart.draw();
});
I would like to replace the setInterval function with something that just replaces the last price data from the database to move the candle up or down, if a new record is added then draw the new candle. I have the script to update the candle or add a new candle I just cannot find a way to do it without re-drawing the whole chart.
You can use the functions for manipulating data to alter the chart.
You can use JS to fetch new data every two seconds, and use addData() to replace the existing data. If that still causes a complete refresh, you'll have to compare the difference between two arrays to determine the difference between the current data and newly fetched data, and use the insert, delete and update methods as described in the docs to alter just the changed data. However, this may still may result in a complete refresh.
You would use AJAX (from JS) to request updated data from a PHP script. The data gets returned to your JS. It's probably easiest to send/receive data in JSON format via jQuery.getJSON.
There's no need to recreate the chart or even reapply the whole data. The AnyStock API provides all you need to update a part of the data. The series will be updated automatically.
For this purpose, you can use addData() function. It replaces all rows with duplicating keys by the last seen row with that key. It means that new points will be added to the table, points with already existing keys in the table will be overridden.
So, all you need is to manage keys and apply points according to your mapping. For details, check the following sample, that simulates exactly what you need - https://playground.anychart.com/Cplq7KMd

Appending new Google Sheets Data into BigQuery Table

So I'm new to all of this, both BigQuery and AppScript (coding in general..) and I'm learning as I go, so maybe to some my question may seem stupid. Please just hear me out.
I have created a script that loads 10 of the most recent data points into a Google Sheets doc from one of my BigQuery tables. Now, when I manually add new data points to the bottom of this table, I would like to have a load script run that uploads that new data back into BigQuery, and appends it to my original table. I read somewhere that just by inserting a new table the data is automatically appended if the table mentioned already exists. However, I haven't tested that part yet since I get stuck on an error earlier up the line..
Below is the load script I have loosely copied from https://developers.google.com/apps-script/advanced/bigquery
function loadCsv() {
var projectId = 'XX';
var datasetId = 'YY';
var tableId = 'daily_stats_testing';
var file = SpreadsheetApp.getActiveSpreadsheet();
var sheet = file.getActiveSheet().getRange("A12:AK10000").getValues();
var data = sheet.getBlob().setContentType('application/octet-stream');
var job = {
configuration: {
load: {
destinationTable: {
projectId: projectId,
datasetId: datasetId,
tableId: tableId
},
skipLeadingRows: 1
}
}
};
job = BigQuery.Jobs.insert(job, projectId, data);
var Msg = "Load started. Check status of it here:" +
"https://bigquery.cloud.google.com/jobs/%s", projectId
Logger.log(Msg);
Browser.msgBox(Msg);
return;
}
Now the error I get (in a variety of forms, since I've been testing stuff out) is that the BigQuery.Jobs function only accepts Blob data, and that the data from my current sheet (with rage A12 marking the first manually imputed row of data) is not a Blob recognizable data set.
Is there any way (any function?) I can use that will directly convert the selected data range and make it Blob compatible?
Does anyone have any recommendation on how to do this more efficiently?
Unfortunately the script has to load directly out of the current, open Spreadsheet sheet, since it is part of a larger script I will be running. Hopefully this isn't too much of a hinder!
Thanks in advance for the help :)
Is there any way (any function?) I can use that will directly convert the selected data range and make it Blob compatible?
There is actually a function that does convert objects into blob type, namely newBlob(data).
To test this I got a range from my spreadsheet and used it.
function blobTest(){
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("A1:C1");
Logger.log(range); //here, range data is of type Range object
var blob = Utilities.newBlob(range);
Logger.log(blob); //here, range data is now of type Blob object
}

Passing MySQL data from flask to JavaScript for Google Charts

I've already checked out some similar questions here: How can I pass data from Flask to JavaScript in a template?
I'm trying to create a google chart using this example , where my data is coming from a database query, which is then parsed and formatted to be passed through Google's datasource python library, then converted into a json string. From there it is supposed to be passed through a JavaScript function in my HTML file in order to populate the Google Charts table. This last part seems to be causing me trouble. Here is the meat of my function in flask:
description = {"count": ("number", "Count"),"type": ("string", "Type")}
data=[]
rows = cur.fetchall()
# formats MySQL data for JSON string
for row in rows:
js = {'type': row[0], 'count': row[1]}
data.append(js)
# Loading it into gviz_api.DataTable (from Google Charts template)
data_table = gviz_api.DataTable(description)
data_table.LoadData(data)
# Create a JSON string. (from google charts template)
json= data_table.ToJSon(columns_order=("type", "count"), order_by="count")
render_template('myhtml.html' , json=json)
at the end of my function in flask, which is then passed through the following JavaScript function in my html file here:
<script>
...
// taken from the Google Charts example
google.load('visualization', '1', {packages:['table']});
google.setOnLoadCallback(drawTable);
var json = '{{ json }}'
function drawTable(json) {
var json_table = new google.visualization.Table(document.getElementById('table_div_json'));
var json_data = new google.visualization.DataTable((json), 0.6);
json_table.draw(json_data, {showRowNumber: true});
}
The chart is not drawn and I am left with only the header for the chart. I don't believe this is an issue with the format of my data or the HTML portion (which I've left out), for it is taken straight from the Google Charts template, so I've been trying to find problems in my JavaScript (which I am fairly new to). Can this string not be passed to the JavaScript function in this fashion? What alternative ways can it be done? Any pointers and suggestions would be great.
Probably have to escape it, something like:
{{json | safe}}

Draw a Chart with Data from Google Analytics Core Reporting API Query

I have a question regarding the Google Analytics Core Reporting API and displaying the result Data within a Chart. I´ve managed to make a query to Analytics, which works just fine. I can choose a start and end-date, the Property and some Dimensions and Metrics in a Web-Formular. Then in return I´m getting all the data, I think in a dataTable Format,because of the Query-Option 'output': 'datatable'
Now i want to display the Data (the DataTable) within a Google Chart. There is the problem. Something is drawn on the screen, but none of the data is being displayed. So I think the drawn Graph is just empty. Logically i tried to create a new dataTable and fill it up with the Data from the Query-Response and then draw it. Somewhere there must be a problem, maybe with the format? I´ve tried many things, but none lead to a proper Chart.
By the Way: If I try to draw a chart with given data, like in the example of the Google Chart Documentation (https://developers.google.com/chart/interactive/docs/quick_start) the graph is drawn without any problem. So I´m guessing its a format-problem.
Here is the Code (a little shorten):
function queryCoreReportingApi(profileId) {
gapi.client.analytics.data.ga.get({
'ids': 'ga:' + profileId,
'start-date': startDate, //Startdate Datepicker
'end-date': endDate, //Enddate Datepicker
'metrics': 'ga:sessions',
'dimensions': dimension,
'filters': 'ga:landingPagePath=#'+service+';'+'ga:deviceCategory=='+device,
'output': 'datatable'
})
.then(function(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
//Output Data in Text-Area
document.getElementById('query-output').value = formattedJson;
document.getElementById('query-output-obj').value = response.result.dataTable;
//Load Chart Lib
google.load('visualization', '1.0', {'packages':['corechart']});
//Create Data-Table and fill up
var data = new google.visualization.DataTable();
data.addColumn('string', 'Browser');
data.addColumn('number', 'Sessions');
response.result.dataTable.rows.forEach(function pushNumericColumn(row) {
data.addRow([row[0], parseInt(row[1])]);
});
var options = {
title: 'Custom Chart',
};
//Draw Chart
var chart = new google.visualization.PieChart(document.getElementById('chart_div2'));
chart.draw(data, options);
}
Output for formattedJson: all the data from the query |
Output for response.result.dataTable: [Object Object] |
Errors: No Errors in the Console
The Authentication process (which is not shown in the code sample) works fine too.
I was able to draw the chart by accessing the "v" property of the row object, like so:
data.addRow([row.c[0].v, parseInt(row.c[1].v)]);

Highcharts Line Chart - Hyperlink on a data point

I am working on an application to create Line Chart using the Highcharts API. This application involves plotting a Date vs. Time Line Chart.
I need to have dynamic hyperlinks, for all or some of the data points.
The data for this chart is being retrieved from a database table and converted into JSON. This JSON is then being parsed by JavaScript and converted into data array that can be consumed by the Highcharts API. There is some data manipulation being done in the JavaScript while converting the data from JSON to data array.
The Highcharts API accepts the input in data array format that comprises of [x, y] combinations.
As I need to have a dynamic hyperlink for all or some of the data points, I have created another array that comprises of the hyperlinks.
I am unable to retrieve the hyperlink URL from the array on the fly as a particular hyperlink is clicked by the user.
I tried using it they was it has been used in this fiddle, http://jsfiddle.net/awasM/1/
A snippet of my code is given below:
series: [{
name: 'Release',
data: dataArray,
URLs: urlArray,
point: {
events: {
click: function() {
var someURL = this.series.userOptions.URLs[this.x];
if (someURL != "undefined")
window.open(someURL);
}
}
}
}]
However, as in my case date (in Unix/Epoch time format) is on x-axis (and time on y-axis), so using the x-axis value does not work.
i hope you could match this code to fix something.
point: {
events: {
click: function() {
var pointObject = this;
var pointindex = pointObject.x;
var pointdata = pointObject.y;
var getIndexOfURL = this.series.userOptions.URLs[pointindex];
var getIndexOfData = this.series.userOptions.data[pointindex];
if (getIndexOfURL){
window.open('http://'+getIndexOfURL);
}
}
}
}

Categories

Resources