自定义 y 轴

问题描述 投票:0回答:1

我有一些带有数据的图表,我希望 y 轴自动适应数据 + 10% 的缓冲区。

自定义工具没有此选项。我没有任何编码背景,但在 ChatGPT 的帮助下,我制作了这个尚未运行的自定义脚本:

function setDynamicYAxis() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var chart = sheet.getCharts()[0]; // Assumes the chart you want to edit is the first one
  var dataRange = sheet.getDataRange();
  var values = dataRange.getValues();
   
  // Find the maximum value in the data range
  var maxValue = 0;
  for (var i = 0; i < values.length; i++) {
    for (var j = 0; j < values[i].length; j++) {
      if (values[i][j] > maxValue) {
        maxValue = values[i][j];
      }
    }
  }

  // Set the new max value with a buffer (e.g., 10% higher)
  var buffer = maxValue * 0.1;
  var newMax = maxValue + buffer;

  // Modify the chart's y-axis maximum value
  var updatedChart = chart.modify()
    .setOption('vAxis.maxValue', newMax)
    .build();

  sheet.updateChart(updatedChart);
}
javascript google-sheets google-apps-script google-sheets-formula
1个回答
0
投票

您可以通过展平矩阵来获得最小值或最大值。

const values = [
  [1, 3, 8],
  [2, 9, 5],
  [7, 4, 0]
];

const flattenedValues = values.flatMap(x => x);
const min = Math.min(...flattenedValues);
const max = Math.max(...flattenedValues);

console.log({ min, max });

如果您的范围包含标题,您将必须将它们切掉:

// Find the maximum value in the data range (exclude headers)
var maxValue = Math.max(...flattenedValues = values.slice(1).flatMap(x => x));

这是工作代码(已验证)

function setDynamicYAxis() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var chart = sheet.getCharts()[0]; // Assumes the chart you want to edit is the first one
  var dataRange = sheet.getDataRange();
  var values = dataRange.getValues();
   
  // Find the maximum value in the data range (exclude headers)
  var maxValue = Math.max(...flattenedValues = values.slice(1).flatMap(x => x));

  // Set the new max value with a buffer (e.g., 10% higher)
  var buffer = maxValue * 0.1;
  var newMax = maxValue + buffer;

  // Modify the chart's y-axis maximum value
  var updatedChart = chart.modify()
    .setOption('vAxis.maxValue', newMax)
    .build();

  sheet.updateChart(updatedChart);
}

这是我的图表用作范围的工作表数据集:

x y
1 6
2 7
3 3
4 99
5 9
6 3
7 2
8 1
9 7
10 4
© www.soinside.com 2019 - 2024. All rights reserved.