Creating a Scatter Graph using Scripting for Google Sheets? - google-apps-script

Google sheet and script: https://docs.google.com/spreadsheets/d/1Vq2MYQzbaRoYg31IRkwNOofJYYOH82ElSdN7miExiVQ/edit?usp=sharing
I currently am trying to create a scatter graph using data that I have been given but only using script, so I am making this scatter graph based on the data in B15 tp W16 but this data is placed in these cells by using the new applied menubar option called "Apply Script".
So if you click:
Apply Script > Activate Script
This will change the cell sizes, change the font size, create a conditional format for the data within cells C3 to W13, and will create a key for the data as well.
Then if you click:
Apply Script > Select Power Input > Select any option
Once you select which row of data you want to view, it'll be applied with cells B15 to W16 (It will make more sense if you try it yourself).
These functions will be applied to any given data that is active, I have 3 sheets within the document below so it demonstrates this.
So now that I have explained how my scripting works so far, I want to know how to script a scatter graph using any given data that is cell B15 to W16. Everything I have demonstrated above is all that I have taught myself in the past 3 days watching videos but I can't find any demonstrations for creating a chart on google scripting anywhere, I have also searched through script.google.com to find the coding needed but I couldn't understand where to start and how to present it. So if anyone can point me in the right direction that'll be great, thank you!
https://docs.google.com/spreadsheets/d/1Vq2MYQzbaRoYg31IRkwNOofJYYOH82ElSdN7miExiVQ/edit?usp=sharing
This is my existing chart script:
function lineGraph() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var row = sheet.getRange( 15, 2, 2, 22).getValues();
sheet.newChart().addRange().asScatterChart().getChartType().SCATTER;
}

Your script is certainly in the right direction, but you have to specify where to place your chart in the sheet by using setPosition.
Also, I added some options for the generated chart to make more sense based on your input.
Sample Code:
function lineGraph() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var row = sheet.getRange("B15:W16");
var chart = sheet.newChart()
.asScatterChart()
.addRange(row)
.setPosition(18,2,0,0)
.setTransposeRowsAndColumns(true)
.build();
sheet.insertChart(chart);
}
Sample Output:
Note that this is bare bones, you can specify more options by adding more methods onto the chartBuilder. Please see reference here:
Embedded Scatter Chart Builder

Related

Set option 'Color' not working in google apps script? (pie chart builder)

Thank you for reading my question. I have been successfully using a script to create pie charts. However, yesterday the code to set pie chart slices' colors, setOption('colors',....), seemed to have stopped working. I have checked a few different types of code to fix it, but I am not able to fix anything related to it. I was wondering if its possible there is a change in the code and it can't be used this way any more? Please find below the code snippet as well as the link to the google sheet that has dummy data etc. Please do let me know how I can fix this? I'm a novice when it comes to coding so I'm a bit lost.
function createPieChart() {
var sheet = SpreadsheetApp.getActiveSheet();
var chartDataRange = sheet.getRange('G2:H5');
var color1 = sheet.getRange('K9').getValue();
var color2 = sheet.getRange('K10').getValue();
var color3 = sheet.getRange('K11').getValue();
var pieChartBuilder = sheet.newChart()
.addRange(chartDataRange)
.setChartType(Charts.ChartType.PIE)
.setPosition(2,1,0,0)
.setOption('width',500).setOption('height',300)
.setOption('pieHole',0.5)
.setOption('colors', [color1,color2,color3])
.build();
sheet.insertChart(pieChartBuilder);
}
Sheet Link: https://docs.google.com/spreadsheets/d/1tPc0KU2uYuN4rO32tW-s6lql_IW57kbDUdSR8ZSkVXY/edit#gid=0
You can report it on Google's Issue Tracker so they can take a look at it.
I have found a similar issue regarding charts with Apps Script, on this issue is about the option visibleInLegend. You can use it as reference to create your one or you can add to that issue: Chart option visibleInLegend not working on Apps Script

How can I set the color for a single data point in a series in Google Sheets script

I decided to create a bar chart inside my Google Sheet, read it in using the Script Editor tool & modify it in place, as I felt this would be easier than creating one from scratch & then adding it to the Sheet. Turns out, using the UI to create the Chart has been much easier than scripting it.
Now, I would like to set the color of only 1 of the data points in a single series to be red, when it's over a certain threshold. So far, I have found that the following snippet can set the color of the entire series, but I can't find anything to set the color of just one data point:
var chart = sheet.getCharts()[0];
chart = chart.modify()
.setOption('series.0.color', 'red')
.build();
sheet.updateChart(chart);
If I try to replace setOption with setColors (.setColors(['green', 'red'])), I get an error saying
TypeError: Cannot find function setColors in object EmbeddedChartBuilder.
According to this reference, setColors can only be used when creating a new chart.
There are numerous articles online about how to change the color of a single data point in a bar chart from the UI. Any pointers on how to change the color programmatically would be much appreciated.
This is how you set the color of a specific series:
var chart = sheet.getCharts()[0];
chart = chart.modify()
.setOption('series.0.color', 'red')
.setOption('series.0.items.0.color', 'blue')
.build();
sheet.updateChart(chart);

Is it possible to add tooltips to google chart using only Class EmbeddedChart?

I have tried to ask a question here where I'd use an embedded chart in gSheets to add tooltips. An answer came back that doesn't work. It DID, however, lead me to search through "google.visualization.DataTable()". This only get me more confused, as I think that creates the chart in another html page.
So, now I'm restating my question to see if what I want is even possible.
GOAL: Have a chart in existing gSheet use custom tooltips from another column like these nifty, dynamic tooltips
PROBLEMS/MY DEFICIENCIES:
1) Many examples on StackOverflow show adding the data in the code itself. Here's one using addTable I need to use the data in my sheet and I don't know how to reference/call it.
2) Most guides in Google use depreciated Uiapp service , and I can't figure out how to copy/learn their code to translate to the new HTML service. Github example
3) If I was to try to use google.visualization.DataTable, it gives me an error, making me think that it wants a more code, and other html files. I can't find the tutorials on HOW to do this. I'm willing to try but can't find the right search terms.
4) Is there a better way to do this? All videos/articles show from 2014 and older.
My code:
function addNewRange) {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('Q:Q').activate();
var sheet = spreadsheet.getActiveSheet();
var charts = sheet.getCharts();
var chart = charts[0];
sheet.removeChart(chart);
chart = sheet.newChart()
.asScatterChart()
.addRange(spreadsheet.getRange('S3:S50004'))
.addRange(spreadsheet.getRange('T3:S50004'))
.addRange(spreadsheet.getRange('Q3:Q50004')) // This the line I need to use as the tooltips
.setOption('useFirstColumnAsDomain', false)
.setPosition(2, 7, 0, 0)
.build();
sheet.insertChart(chart);
};

correctly insert chart from Google Sheet into Document using Google Apps Script

I want to copy charts from my spreadsheet to a document using Google apps script.
Inserting the charts works, but there is an issue with a) permissions and b) formatting.
Charts can be inserted as follows:
var b = d.getBody();
var charts = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("charts").getCharts();
for (var i in charts) {
b.appendImage(charts[i]);
Logger.log(charts[i].getBlob().getName()); // correct: "chart.png"
}
When I manually copy the chart and paste it in the document, the formatting is exactly as in the spreadsheet.
when I copy using the script, formatting looks very strange or even causes an error (for the line chart with dates on the x-axis it shows an image with the text Data column(s) for axis #1 cannot be of type string)
Top row is manually copied, bottom row is the result of the script.
The second -related?- issue: the spreadsheet needs to be shared ("anyone with the link can view"), otherwise it shows the image (correct name, width, height, etc.) as an error message: User not signed-in. Sign in.
Any suggestions how to insert the chart with the correct formatting and without having to share the spreadsheet?
Stefan pointed me in the right direction (thanks!).
It appears the rendering is done quite differently when pasting/saving images.
Different axis settings, colors, theme, etc.
I ended up manually creating the chart. E.g. for the first bar chart, the following results in a chart that appears the same in the spreadsheet and in the document:
var chart = dest.newChart();
chart
.setChartType(Charts.ChartType.BAR)
.addRange(myrange)
.setPosition(2,8,0,0)
.setOption("theme","maximized")
.setOption("colors",["#3366CC","#FF9900","#DC3912","#109618"])
.setOption('isStacked', true)
.setOption('width', 500)
.setOption('height', 130)
.setOption('hAxis.viewWindow.max', countActions)
.setOption('vAxis.gridlines.count', 0)
.setOption('legend', {position: 'in', textStyle: {fontSize: 12}})
var chart = chart.build();
dest.insertChart(chart);
I also had to change the data range, as it appears the following chart settings can not be set manually.
switch rows/columns
use first row as header
To solve that I have manually transposed the range in the spreadsheet (=TRANSPOSE(original_range)) and let myrange point to that new range, and I have added an empty column so that one is used as an empty header.
I have not looked at the line chart yet, it could be the Chart API can not create a timeline in the same way as the Spreadsheet does.
For what its worth I just used the original script in a simple report builder that takes data and charts from a Google Sheet and auto-generates a report containing them for any user. It worked very easily. Was a slightly modified version of the following
var charts =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("charts").getCharts();
for (var i in charts) {
doc.getBody.appendImage(charts[i]);
Logger.log(charts[i].getBlob().getName())};
where in my script "doc" is a var that repr
Have a look at:
Reading title of Graph
When I was playing around, I remember having issues as well like you described. When I made sure all the required fields were added in the graph (so no skipping of data elements), it worked fine.
Strangly, skipping data elements didn't seem to cause issues in the graph (neither with manually copying & pasting).

Displaying Google Spreadsheets data in Google Sites as HTML?

I have a google spreadsheet and I'm trying to build a webpage using Google sites. I don't want to embed the whole sheet, or even a range of cells. I just want my webpage to display text from some cells in the spreadsheet, and I want to be able to style that text using HTML.
For example, in the value in cell A1 is "There are 3 games today".
I want to be able to put this text in my webpage and then give it a font size, alignment, and put it in a box with a border and curved corners (border radius).
I think there may be several ways of acheiving this but the closest I have got is by inserting an 'Apps script gadget' into the page and using the doGet() method:
function doGet(e){
var app = UiApp.createApplication();
var ss = SpreadsheetApp.openById('SPREADSHEET_KEY');
var sheet = ss.getSheetByName("Sheet1");
var range = sheet.getRange('A1');
var dataRange = range.getValue().toString();
app.add(app.createHTML("There are " + dataRange + " games today"))
return app;
}
but I dont know how to then add HTML to the webpage to make it look fancy.
I haven't even been able to set anything within the script e.g. font alignment. I've tried
.setHorizontalAlignment('center')
but I keep getting errors such as "Cannot find method (class)setHorizontalAlignment(string)". Can anyone kindly point me in the right direction?
Many thanks in advance
Most of the style attributes can be set with .setStyleAttributes().
.setStyleAttribute("fontSize","200%");
Note: Instead of writing font-size or margin-left, you need to use camelCase.
.setStyleAttributes({marginLeft:"15px",marginTop:"22px"});
These are just a few examples of how to use this.
In order to use horizontal alignment, you should use
.setHorizontalAlignment(UiApp.HorizontalAlignment.CENTER);
Use the autocomplete feature of Google Scripts to see all the options that you can use.
If you're already familiar with HTML, then consider using HTML templates to pull variables from the spreadsheet into the HTML. Templated HTML