Google Sheet api 中的 Python 图表比例

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

我可以使用 python 在 Google 表格中创建图表,但我找不到如何将柱形图的垂直轴刻度设置为对数。可以使用图形编辑器手动执行,但我不知道如何使用 python 程序执行相同的操作。 提前感谢任何帮助。

python-3.x charts google-sheets-api scale logarithm
1个回答
0
投票

问题和解决方法:

在现阶段,不幸的是,柱形图纵轴的比例似乎无法通过Sheets API修改。那么,作为未来的请求将此问题报告给 Google 问题跟踪器怎么样? https://issuetracker.google.com/

但是,幸运的是,当使用Google Apps Script时,就可以实现。在这个答案中,作为当前的解决方法,我想建议使用 Google Apps 脚本和 Python 来实现您的目标。

在此解决方法中,使用部署为 Web 应用程序的 Google Apps 脚本修改垂直轴的比例。该脚本可以通过Python脚本运行。

用途:

1.创建一个新的 Google Apps 脚本项目。

Web Apps 的示例脚本是 Google Apps 脚本。请创建一个 Google Apps 脚本项目。

如果您想直接创建,请访问https://script.new/。在这种情况下,如果您尚未登录 Google,则会打开登录屏幕。请登录谷歌。这样,Google Apps 脚本的脚本编辑器就打开了。

2.示例脚本。

请将以下脚本复制并粘贴到创建的 Google Apps 脚本项目中并保存脚本。

function doGet(e) {
  const { spreadsheetId, chartId } = e.parameter;
  const sheets = SpreadsheetApp.openById(spreadsheetId).getSheets();
  const res = sheets.some(sheet => {
    const chart = sheet.getCharts().find(c => c.getChartId() == chartId && c.modify().getChartType() == Charts.ChartType.COLUMN);
    if (chart) {
      sheet.updateChart(chart.modify().asColumnChart().useLogScale().build());
      return true;
    }
    return false;
  });
  return ContentService.createTextOutput(res ? "Done." : `Chart with chart ID ${chartId} and COLUMN chart was not found.`);
}

3.部署 Web 应用程序。

详细信息可以看官方文档

  1. 在脚本编辑器中,请点击脚本编辑器右上角的“单击部署”->“新建部署”。
  2. 请点击“选择类型”->“Web App”。
  3. 请在“部署配置”字段中输入Web App的信息。
  4. 请为“执行为”选择“我”
  5. 请为“谁有权访问”选择“任何人”
    • 在这种情况下,用户不需要使用访问令牌。所以请将此作为测试用例。
    • 当然,您也可以使用访问令牌访问您的Web应用程序。请查看此报告
  6. 请点击“部署”按钮。
  7. 复制 Web 应用程序的 URL。就像
    https://script.google.com/macros/s/###/exec

4.测试。

为了测试此 Web 应用程序,请测试以下示例 Python 脚本。请设置您的 Web 应用程序 URL、您的电子表格 ID 和您的图表 ID。图表ID可以通过“方法:spreadsheets.get”获取。

import requests

url = "https://script.google.com/macros/s/###/exec"
url += "?spreadsheetId=###&chartId=###"
res = requests.get(url)
print(res.text)
  • 当您的 Web 应用程序正确部署且电子表格 ID 和图表 ID 为有效值时,运行此 Python 脚本时,柱形图纵轴的刻度将更改为对数刻度。
  • 出现错误时,请再次确认Web Apps的设置。

参考资料:

© www.soinside.com 2019 - 2024. All rights reserved.