How to display data series label in google sheets charts - google-apps-script

I made a google Apps script to modify a chart and I would like to display the data label of the series number 0 but the line .setOption('series',{ 1:{color: '#2ecc71'}}) (where I change the color of the series 1) remove the data label of the series 0.
var Vmax =1.1*ss.getRangeByName("D285").getValue(); //get max and min here (before, it's equal to 0)
var Vmin =0.9*ss.getRangeByName("C285").getValue();
var sheet = SpreadsheetApp.getActiveSheet();
var chart = sheet.getCharts()[46];
chart = chart.modify()
.setChartType(Charts.ChartType.AREA)
.setOption('title',string)
.setOption('vAxes', {0: {textStyle: {fontSize: 10}, titleTextStyle: {fontSize : 8}, viewWindow: {min: Vmin, max:Vmax}}})
.setOption('series',{ 1:{color: '#2ecc71'}})
.setOption('titleTextStyle',{alignment:"center"})
.setOption('animation.startup',true)
.setOption('animation.duration', 5000)
.setOption('hAxis.slantedText',true)
.setPosition(290,6,0,0)
.build();
Logger.log(Vmax);
Logger.log(Vmin);
sheet.updateChart(chart);
This is what I have :
And this is what I want :

Your comments helped me solve this problem. I didn't know that the key word is annotations.
here is the code I used to update the dataLabel font and color
.setOption("series", {1 : {dataLabel: "value"}}) //this creates the data label
.setOption("series", {1: {annotations: {textStyle : {fontSize : 24, color : 'white'}}}}) //this updates the color and font size of the data label.
I run this through updateChart
I hope this helps

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

How to change tick labels in d3.svg.axis()

I am trying to edit an HTML code of a map. And I want to change the labels of the scalebar by three orders of magnitude less, I mean, if the value is 100000 the scalebar should show 100, without changing the scale domain, just the labels.
Actual scalebar
And these are the values i want to appear in the scalebar:
[0.0, 189.0, 377.0, 566.0, 755.0, 943.0, 1132.0, 1320.0, 1509.0]
I know maybe it's with .tickFormart but i don't know which format i have to use. Here is the code:
color_map_0caac4580c6c4cdd8684ab303e6dc8e4.x = d3.scale.linear()
.domain([0.0, 1509134.0])
.range([0, 400]);
color_map_0caac4580c6c4cdd8684ab303e6dc8e4.legend = L.control({position: 'topright'});
color_map_0caac4580c6c4cdd8684ab303e6dc8e4.legend.onAdd = function (map) {var div = L.DomUtil.create('div', 'legend'); return div};
color_map_0caac4580c6c4cdd8684ab303e6dc8e4.legend.addTo(map_327a7d6fcd834e0aa3fc248c7a9557c9);
color_map_0caac4580c6c4cdd8684ab303e6dc8e4.xAxis = d3.svg.axis()
.scale(color_map_0caac4580c6c4cdd8684ab303e6dc8e4.x)
.orient("top")
.tickSize(1)
.tickValues([0.0, 188641.75, 377283.5, 565925.25, 754567.0, 943208.75, 1131850.5, 1320492.25, 1509134.0])
.tickFormat([0.0, 189.0, 377.0, 566.0, 755.0, 943.0, 1132.0, 1320.0, 1509.0]);
You can ignore this color_map_0caac4580c6c4cdd8684ab303e6dc8e4it's a Folium thing (Python)
You can pass your own custom function to tickFormat. The input to this function is the tick value and the output is what you want the label to be. In your case, you could do
.tickFormat(d => d / 1000)

How to remove bars for those bars with zero value in Chartjs bar chart?

Even if the bars have value of zero in bar chart created using chartjs, they still show a visible bar. This is misleading for my purpose and I would like to have it removed and show nothing there (meaning that, I still want to show labels with zero value but not the bar). I tried changing min value of y-axis but it doesn't make a difference. The image below shows this problem for columns 56, 60 and 78. Is there a way to get rid of this? Thanks!
And here is my script:
<div>
<canvas id="canvas_bar" height="250", width = "300" ></canvas>
</div>
<script>
var barChartData = {
labels : [56, 60, 78, 90],
datasets : [
{ fillColor : "rgba(139,0,0,0.5)",
strokeColor : "rgba(220,220,220,0.8)",
data : [20.0, 0, 0, 50] },
{ fillColor : "rgba(1,187,205,0.5)",
strokeColor : "rgba(151,187,205,0.8)",
data : [0, 0.0, 40.0, 10] }
]
}
window.onload = function(){
var ctx = document.getElementById("canvas_bar").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
animation: false,
responsive : false,
barValueSpacing : 15,
scaleShowVerticalLines: false,
});
}
</script>
By default the barStrokeWidth value is 2.
Just add this :
barStrokeWidth:0,
or :
barShowStroke : false,
In your options.
http://www.chartjs.org/docs/#bar-chart-chart-options
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
update December 2021:
barStrokeWidth is deprecated.
I used inflateAmount: 0 (default value is auto) and it fixed the issue for me
docs: https://www.chartjs.org/docs/latest/charts/bar.html#dataset-properties
if barShowStroke : true
not working try to
barRadius: 0
I found that you can add skipNull property to dataset objects. And bars where value is null or undefined won't take any space.
https://www.chartjs.org/docs/3.2.0/charts/bar.html

pieChart pieSliceText visibilty

Piechart sliceLabel is not shown for smaller slices.
My piechart image looks like :
https://drive.google.com/file/d/0B1dlb5k9SpLPYXJRRmRXSkpTUXM/view?usp=sharing
ActualRequired Piechart should like: https://drive.google.com/file/d/0B1dlb5k9SpLPOFBzNUw2Tkdsblk/view?usp=sharing
Code Snippet :
var dataTest = google.visualization.arrayToDataTable([ ['Country','Population'], ['India', 10], ['Australia', 1], ['Sri Lanka', 5.3], ['New Zeland', 9], ['Others', cell[0][5]],
]);
google.visualization.PieChart(document.getElementById('popStat')).draw(dataTest,{sliceVisibilityThreshold:0,chartArea:{left:'15%',top:'15%',width:'100%',height:'100%'}, title: 'Population Stats',});
It is because the slice relative part, below which a slice will not show individually. All slices that have not passed this threshold will be combined to a single slice, whose size is the sum of all their sizes. Default is not to show individually any slice which is smaller than 1/2 degree. You can modify the sliceVisibilityThreshold to change this effect. You can just set the sliceVisibilityThreshold option to 0. This will force all the legends to show.
See the reference: https://developers.google.com/chart/interactive/docs/gallery/piechart

Customising Google Bar Chart Using Google App 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?