Customising Google Bar Chart Using Google App Script - google-apps-script

I am currently having some issues configuring a simple graph using Google App Scripts. I seem to be unable to find the correct documentation in order to progress any further!
I have everything hooked up pulling data from a couple of spreadsheets, so that aspect is fine!
I see that there are various ways in order to customise the looks of a chart and there are tools available for example:
http://imagecharteditor.appspot.com/
http://code.google.com/apis/ajax/playground/?type=visualization
I wish to add colours to my bar charts like in this example
http://code.google.com/apis/ajax/playground/?type=visualization#image_multicolor_bar_chart
Additionally in the first link there are options to create sections using the range marker tool. I was hoping that with these tools I could copy the code across to use in my App Script Chart.
The only way I can see this working is using .setOption(string, object)
I've tried this...
var data = Charts.newDataTable()
.addColumn(Charts.ColumnType.STRING, 'Month')
.addColumn(Charts.ColumnType.NUMBER, 'Mark Achieved')
for(var x=0; x < ChartData.length;x++){
data.addRow(ChartData[x]);
}
data.build();
var chart = Charts.newColumnChart()
.setDataTable(data)
.setDimensions(1000, 600)
.setRange(0, 100)
.setTitle('Test Scores')
.setLegendPosition(Charts.Position.BOTTOM)
.setOption('options',{cht: 'bvs', chco: 'A2C180,3D7930', max: 100})
.build();
app.add(chart);
any help would be much appreciated!
EDIT

The options you are trying to use are applicable to the static image charts (which are now deprecated), and won't work with ColumnCharts. ColumnCharts color the bars by series, not by data point, so if you want multi-colored bars, you have to separate them out into different data series. I wrote a hack that does this (see on jsfiddle for the standard javascript version). My reading of the AppsScript implementation of the Visualization API seems to preclude using calculated columns in the DataViews, but it is possible that the documentation is incomplete here. Try creating a view like this:
// add one calculated column for each month
var dataViewDefinition = Charts.newDataViewDefinition().setColumns([0, {
type: Charts.ColumnType.NUMBER,
label: 'Mark Achieved',
calc: function (dt, row) {
if (dt.getValue(row, 0) == 'January') ? dt.getValue(row, 1) : null;
}
}, {
type: Charts.ColumnType.NUMBER,
label: 'Mark Achieved',
calc: function (dt, row) {
if (dt.getValue(row, 0) == 'February') ? dt.getValue(row, 1) : null;
}
}/*...*/]);
It is probable that this needs to be tweaked, and possible that it won't work at all, in which case you would have to either change the query of the spreadsheet or rearrange the structure of the spreadsheet.
As far as adding the ranges to the chart, can you elaborate more on what you would like those to look like?

Related

How do I get a multiple-line subtitle in google sheet charts?

I am creating a bar chart in google sheet, recording it with a macro, and running the code for different data cases.
When the subtitle is too long, there is missing text on the chart, shown with ellipses (...)
Increasing the chart's width reveals more of the text but not all.
Increasing the chart's height does nothing! (It reveals a long title, but not a long subtitle!)
Adding a line break doesn't work. When using one, all I can see is the first line of the subtitle, while the others stay completely hidden...
How can I have a subtitle that shows all of the text I want to display?
Given that titles are responsive in both the horizontal and vertical axes, it's really odd for subtitles not to be.
Thank you
---- Edit ----
The script helps automate things, but I don't think that it adds new functionalities. That being said, the code I use is the following:
function Macro3() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
var chart = sheet.newChart()
.asBarChart()
.addRange(spreadsheet.getActiveRange())
.setMergeStrategy(Charts.ChartMergeStrategy.MERGE_COLUMNS)
.setTransposeRowsAndColumns(false)
.setNumHeaders(4)
.setHiddenDimensionStrategy(Charts.ChartHiddenDimensionStrategy.IGNORE_BOTH)
.setOption('bubble.stroke', '#000000')
.setOption('useFirstColumnAsDomain', true)
.setOption('isStacked', 'false')
.setOption('su', SpreadsheetApp.getActiveSheebtitlet().getRange("B2:B2").getValue())
.setOption('title', SpreadsheetApp.getActiveSheet().getRange("B1:B1").getValue())
.setOption('annotations.domain.textStyle.color', '#808080')
.setOption('textStyle.color', '#000000')
.setOption('legend.textStyle.color', '#1a1a1a')
.setOption('subtitleTextStyle.color', '#999999')
.setOption('titleTextStyle.color', '#757575')
.setOption('annotations.total.textStyle.color', '#808080')
.setXAxisTitle(SpreadsheetApp.getActiveSheet().getRange("B4:B4").getValue())
.setOption('hAxis.textStyle.color', '#000000')
.setYAxisTitle(SpreadsheetApp.getActiveSheet().getRange("A4:A4").getValue())
.setOption('vAxes.0.textStyle.color', '#000000')
.setPosition(2, 1, 30, 0)
.build();
sheet.insertChart(chart);
};
I wanted to include a screenshot of the Google sheet this macro is used upon, but this is my 1st post on stackoverflow and apparently I need at least 10 reputation to post images.
If you think it would help to share this screenshot and there is a neat way of doing it, please let me know.
Thanks again
In the current state it is not possible to add multiple lines to the subtitles of Google Sheets charts. Therefore I recommend you to go to Help > Help Sheets to Improve and add this request. Alternatively, you can use this template to request this functionality for Apps Script, for example, allowing EmbeddedCharts to have titles written with HTMLService.
Possible workarounds:
Change the font size according to the string length.
As I told you in the comments, you can measure the amount of words your subtitle has and according to that, apply different font sizes. For example:
function calcFontSize(subtitle){
const lenS = subtitle.split(" ").length
if(lenS > 12) return 8
if(len <= 12) return 12
}
// Inside your macro
.setOption(
'subtitleTextStyle.fontSize',
calcFontSize(sheet.getRange('B2:B2').getValue())
)
PROS : You have a "responsive" subtitle.
CONS: As you say In long texts ... The text becomes too small to read
Use Charts Service to create your chart
As this service allows you to add jump lines to your title, you can achieve what you want:
function createGoogleChart() {
// extracted from here https://developers.google.com/apps-script/reference/charts/charts
const data = Charts.newDataTable()
.addColumn(Charts.ColumnType.STRING, 'Month')
.addColumn(Charts.ColumnType.NUMBER, 'In Store')
.addColumn(Charts.ColumnType.NUMBER, 'Online')
.addRow(['January', 10, 1])
.addRow(['February', 12, 1])
.addRow(['March', 20, 2])
.addRow(['April', 25, 3])
.addRow(['May', 30, 4])
.build();
const chart = Charts.newAreaChart()
.setDataTable(data)
.setStacked()
.setRange(0, 40)
.setTitle("My title\nMy long long long long long \n long long long long \n subtitle")
.build();
SpreadsheetApp.getActiveSheet().insertImage(
chart.getAs('image/png'), 10, 10
)
}
PROS : You can achieve what you need.
CONS:
You insert a still image (not editable)
There is no default subtitle option
You have to build it from Apps Script, and adapt it to your macro

In Google Earth Engine: Most efficiently reduceRegions over each image in ImageCollection, saving mean as a Feature property?

I have a FeatureCollection made up of many (100-200) polygons ('ftr_polygons'). I also have an ImageCollection made up of monthly median Landsat8 bands and indices ('byMonth'). I want to ReduceRegions and save a median (or mean) spatial average from each polygon in the FeatureCollection. End goal is to export to csv a timeseries of monthly mean bands/indices within each polygons over multiple years (2013-2019).
With the code below, I am able to do this for ~1 year, but any more than that, and I get an error: 'FeatureCollection (Error) Computation timed out’. Is there a better way to do this?
// define the function that will grab median (or mean) spatial reductions for each polygon, for each month
var extractdata = function(medianImage,ftr_polygons) {
var date_start = ee.Date(medianImage.get('system:time_start')).format("YYYY-MM"); // get date as string to append to each property
// spatial MEDIAN
ftr_polygons = medianImage.reduceRegions({ // create feature collection with new properties, bands for each month, uniquely named
collection: ftr_polygons,
reducer: ee.Reducer.median(),
scale: 30,
tileScale: 1}); // tile scale
var ftr_polygons_propnames = ftr_polygons.first().propertyNames(); // get property names first
var ftr_polygons_newnames = ftr_polygons_propnames.replace('NDVI_median',
ee.String('NDVI_median_').cat(date_start)); //replace property names with band+date
ftr_polygons_newnames = ftr_polygons_newnames.replace('EVI_median',
ee.String('EVI_median_').cat(date_start)); //replace property names with band+date
ftr_polygons_newnames = ftr_polygons_newnames.replace('NIRv_median',
ee.String('NIRv_median_').cat(date_start)) ; //replace property names with band+date
ftr_polygons = ftr_polygons.map(function(f) {return f.select(ftr_polygons_propnames,ftr_polygons_newnames)});
return ftr_polygons;
};
// apply the function over ImageCollection byMonth, beginning with feature collection ftr_polygons
var ftr_polygons = ee.FeatureCollection(byMonth.iterate(extractdata,ftr_polygons));
// remove geometry on each feature before printing or exporting
var myproperties=function(feature){
feature=ee.Feature(feature).setGeometry(null);
return feature;
};
var ftr_polygon_export = ftr_polygon.map(myproperties)
print(ftr_polygon_export.limit(1), 'For export w monthly properties');
Maybe this answer: https://stackoverflow.com/a/48412324/12393507 alludes to a better way:
The same approach can be used with reduceRegions() as well, mapping over images and then over regions. However, you will have to map over the resulting features to set dates.
I would appreciate more info on this approach.
Thanks.
For computationally intensive operations that will run for a long time you should always export your results instead of visualizing/printing them.
For more info read through this section of the debugging page in the Earth Engine manual.

Is it possible to convert a Chart to and EmbeddedChart?

I'm attempting to Create a few charts out of a Sheet of data, but the charts are grabbing sort of specific data so I have found it advantageous to use the DataTableBuilder class. I am able to specify labels for the data more easily than I can from the original sheet. However, I cannot embed a Chart Class into a Sheet. Is it possible to either convert a Chart to an EmbeddedChart or use a DataTable to create an EmbeddedChart?I'm attempting to Create a few charts out of a Sheet of data, but the charts are grabbing sort of specific data so I have found it advantageous to use the DataTableBuilder class. I am able to specify labels for the data more easily than I can from the original sheet. However, I cannot embed a Chart Class into a Sheet. Is it possible to either convert a Chart to an EmbeddedChart or use a DataTable to create an EmbeddedChart?
This is the data below, and I need only the last column (5/11) and I don't need the total row. So its not a concise range, else I would just use the Embedded chart builder.
May 5/1 5/2 5/3 5/11
Critical 0 0 0 0
High 0 0 0 0
Call Immediate 4 11 4 3
Daytime Call 3 3 6 1
Totals 7 14 10 4
Below is the how I've built the Chart in which dailyTotals is a range of [0, 0, 3, 1]. This works fine, but I can't label anything.
var dailyChart = LOB.newChart()
.setChartType(Charts.ChartType.BAR)
.setOption('title', LOB.getName())
.addRange(dailyTotals)
.build();
LOB.insertChart(dailyChart);
Below is building the DataTable, this time daily totals is just an array. But this gives me labels.
dailyTable = Charts.newDataTable()
.addColumn(Charts.ColumnType.STRING, "Priority")
.addColumn(Charts.ColumnType.NUMBER, "Incidents")
.addRow('P1', dailyTotals[0])
.addRow('P2', dailyTotals[1])
.addRow('P3', dailyTotals[2])
.addRow('P4', dailyTotals[3])
.build();
How can I either use a DataTable to create an EmbeddedChart? or how can I turn a Chart into and Embedded chart?
I actually figured out a solution that worked for me before I got a response from anyone. It involves using a legend to determine which bar is which, rather than labels along the x-axis, but it totally covers my requirements and might help out some one else out.
var dailySeries = {
0:{color: 'blue', labelInLegend: 'P1'},
1:{color: 'red', labelInLegend: 'P2'},
2:{color: 'yellow', labelInLegend: 'P3'},
3:{color: 'green', labelInLegend: 'P4'}
}
var dailyChart = LOB.newChart()
.setPosition(8, 27, 0, 0)
.setChartType(Charts.ChartType.BAR)
.asColumnChart()
.setOption('title', LOB.getName())
.addRange(dailyTotals.getCell(1, 1))
.addRange(dailyTotals.getCell(2, 1))
.addRange(dailyTotals.getCell(3, 1))
.addRange(dailyTotals.getCell(4, 1))
.setOption('series', dailySeries)
.build();
LOB.insertChart(dailyChart);
You would need to re-create the below range somewhere else in the sheet and add that as range instead.
A B
P1 0
P2 0
P3 3
P4 1
The range [P1, P2, P3, P4] can also be somewhere else. Then you can add both ranges:
.addRange([P1 to P4 range])
.addRange(dailyTotals)
.setOption('useFirstColumnAsDomain','true')

Rotate node to look at another node

Cocos Creator - I have a node that I want to rotate towards another node, here is the code I'm using:
update: function (dt) {
this.rotate();
},
rotate: function () {
var diff = this.target.position - this.node.position;
var angle = Math.atan2(diff.x, diff.y);
this.node.rotation = cc.radiansToDegress(angle);
},
But it's not rotating at all, I tried to search the docs but couldn't find anything helpful.
var diff = this.target.position - this.node.position;
You're basically trying to subtract an object from an object. Check
{'x':2, 'y':3} - {'x':4, 'y':6}
in your JS console. The result is NaN
You need to subtract each dimension manually.
var diff = {
'x' : this.target.position.x - this.node.position.x,
'y':this.target.position.y - this.node.position.y
};
Apologies to necro this question, but since this is a top search result I just wanted to add that the problem here is that the signature of Math.atan2 takes it's coordinates backwards:
Syntax:
Math.atan2(y, x)
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2

D3 reusable multi-line chart with JSON data

I'm trying to do some re-factoring on my charts to make them re-usable using this as a guide: http://bost.ocks.org/mike/chart/
I'm having problems drawing the lines in my multi-line graph though - specifically passing the data to the x and y values. If I hard code the element names it works, but if I try to use the xValue and yValue objects this does not work. I'm assuming that this is because I'm trying to call a function within the parameter of an other object, but I'm not sure how to get around this. In the exmaple Mike uses d[0] and d[1], but this won't work with JSON data (or I'm not sure how to make it work).
I've posted this JSFiddle so you can see the code. The problem lines are 125 to 131 which in turn is being called from line 165.
var main_line = d3.svg.line()
.interpolate("cardinal")
// Hard coding the elements works
//.x(function(d) { return main_x(d.date); })
//.y(function(d) { return main_y(d.buildFixTime); });
// Passing xValue and yValue does not work
.x(function(d) { return main_x(xValue); })
.y(function(d) { return main_y(yValue); });
http://jsfiddle.net/goodspeedj/fDyLY/
Thank you in advance.
You need to redefine your accessor method within .x() and .y(). The accessor method defines the way that a datum is pulled out of the data that is bound to the selection that you call the line generator on.
Suppose you have a relatively flat data structure such as the following.
data = [{x : 1, y : 2}, {x:1, y:3}, {x:4, y:5}];
You then bind the data to a selection with the following statement
d3.select("body").datum(data).append("path").attr("d",lineGenerator);
Quite a bit is going on underneath this statement. I'll give you a bit more of a walkthrough after showing you a commonly used example.
The important aspect to understand is that similarly to other calls in d3 such as
var exampleRectangles = d3.select("body")
.data(data).enter()
.append("rect")
.attr("width",2)
.attr("height", 3)
.attr("x",function(datum){return datum.x}) // pay attention to this line
.attr("y",0);
d3 is implicitly iterating over each element in your data. For each datum in your data array, in this case there is a total of three datum, you are going to add a rectangle to the dom.
In the line that I tell you to pay attention to you notice that you're defining an anonymous (unnamed) function. What is that datum parameter coming from? It's implicitly being passed to your anonymous function.
So each rectangle has it's own corresponding datum {x : 1, y : 2}, {x:1, y:3}, {x:4, y:5} respectively. Each rectangle's x coordinate is defined by the respective datum.x attribute. Under the sheets, d3 is implicitly looping over the data array that you've defined. A similar approach to the example d3 code could be written as above.
for (var i = 0; i < data.length; i++)
{
d3.select("body").append("rect")
.attr("width",2)
.attr("height", 3)
.attr("x",data[i].x)
.attr("y",0);
}
This follows from the notion of data driven documents (d3). For each item added (a rectangle in the above example a piece of data is tied to it. In the above example you see that there is something kind of similar to your .x() and .y() accessor functions :
.attr("x",function(datum){return datum.x})
This function is telling d3 how to filter over the total datum that's being passed to the .attr() accessor method.
So, you need to determine which data you need to get a hold of to make your .attr("d", lineGenerator)call make sense. The difference between your.datum(data)call and the typical.data(data)call is that instead of parceling the data that's being passed to.data(data)`, the whole array is given as a single piece of data to the line generator function (similar to main_line(data), wherein it will again implicitly loop over the points to construct your path.
So, what you need to do is determine what a single datum will be defined as for your function to operate on.
I'm not going to define that as I don't seem to know quite which information you are operating on, but I would hazard a guess at something like.
.x(xAccessor)
.y(yAccessor)
function xAccessor(datum)
{
return xScale(datum._id.month);
}
function yAccessor(datum)
{
return yScale(datum.buildFixTime);
}
The way you have it set up, xValue and yValue are functions; you have to actually execute them on something to get a value back.
.x(function(d) { return main_x( xValue(d) ); })
.y(function(d) { return main_y( yValue(d) ); });
If you weren't using a scale, you could use
.x(xValue)
.y(yValue);
but only because if you pass in a function d3 executes it for you with the data as a parameter. And that only works for d3 methods that expect functions as possible input -- the scale functions expect data values as input.
I wrote a long piece work for another user last week that you may find useful, explaining methods that accept functions as parameters.