【问题标题】:Google Sheets chart - dynamic min max Y axis from dataGoogle表格图表-来自数据的动态最小最大Y轴
【发布时间】:2022-01-02 21:17:59
【问题描述】:
我使用从 API 提取的数据在 Google 表格中创建了一个折线图。数据每小时都在变化,因此图表数据的最小值和最大值也会变化。
我想知道是否有脚本可以从一列数据中查找最小值和最大值,并使用这些值动态设置 Y 轴的最小值/最大值。
目前我可以看到更改 Y 轴最小值最大值的唯一方法是在图表编辑器中手动更改,但输入只接受数字,而不是公式,因此最小值最大值是刚性的。
【问题讨论】:
标签:
google-sheets
dynamic
charts
【解决方案1】:
// Only applies to first y axis
// Only applies to charts on active spreadsheet
// Allows for multiple series
// Takes approx 3 seconds per 10 charts to run
// Change Sheet1 for your sheet name
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1')
var config = {
// y-axis max is this factor higher than your chart's max value
// For example if your max value is 100 and scaleUpBuffer is 0.1,
// the y-axis max value will be set to 100 * (1 + 0.1) = 110
scaleUpBuffer: 0.0001,
// y-axis min is this factor lower than your chart's min value
scaleDownBuffer: 0.0001,
// If / when google fix goes through,
// set this to true and run fixCharts() to get default scaling back
// This sets min and max y axis values to null (the default)
restoreDefault: false,
}
function fixCharts() {
var minMaxY1;
sheet.getCharts().forEach(function (chart) {
minMaxY1 = config.restoreDefault ? [null, null] : getChartMinMaxY(chart, config);
updatedChart = chart
.modify()
.setOption('vAxes', {0: {viewWindow: {min: minMaxY1[0], max: minMaxY1[1]}}})
.build();
sheet.updateChart(updatedChart);
})
}
function getChartMinMaxY(chart, config) {
var chartRangeArray,
y1 = [];
chart.getRanges().forEach(function(chartRange) {
chartRangeArray = chartRange.getValues();
chartRangeArray.forEach(function(row) {
for (var i=1;i<row.length;i++) {
// loops all series, assumes all on 1st y axis
if (typeof row[i] == 'number') {
// ignores blanks, headers, junk strings etc.
y1.push(row[i]);
}
}
});
});
return [
Math.min.apply(null, y1) * (1 - config.scaleDownBuffer),
Math.max.apply(null, y1) * (1 + config.scaleUpBuffer)
];
}