You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用xlwings创建组合图表遇KeyError: 'combination'如何解决?

解决xlwings创建组合图表的KeyError问题

直接设置chart.chart_type = 'combination'会报错,因为xlwings的图表类型映射表里没有这个值,官方文档的描述存在误导性。组合图表需要通过单独设置每个数据系列的图表类型来实现,以下是可行的示例代码:

import xlwings as xw

# 初始化工作簿和工作表
wb = xw.Book()
ws = wb.sheets['Sheet1']

# 填充示例数据(对应你提到的B3:E4区域)
ws.range('B3').value = ['Q1', 'Q2', 'Q3', 'Q4']
ws.range('C3').value = [80, 120, 95, 130]
ws.range('D3').value = [90, 110, 105, 140]
ws.range('E3').value = [75, 130, 85, 150]
ws.range('C4').value = [100, 150, 120, 180]

# 创建图表并绑定数据源
chart = ws.charts.add(left=200, top=50)
chart.set_source_data(ws.range('B3:E4'))

# 配置组合图表:将第一个系列设为柱形图,第二个系列设为折线图
chart.series[0].chart_type = 'column_clustered'
chart.series[1].chart_type = 'line'

# 可选:给折线图系列设置次坐标轴,更清晰区分数值差异
chart.series[1].axis_group = 2

关键说明:

  • 先创建基础图表(默认是柱形图),无需指定combination类型
  • 通过chart.series[index]定位每个数据系列,单独设置chart_type,支持的类型包括column_clustered、line、area等
  • axis_group=2表示使用次坐标轴,适合数值差异较大的系列组合

内容的提问来源于stack exchange,提问作者anallaser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 03:25:01