Openpyxl图表 - 来自随机未连接单元格的数据系列可能吗?

时间:2016-11-14 20:18:21

标签: python excel charts openpyxl

我目前正在尝试使用python模块openpyxl,尝试在工作中自动执行某些任务并自动生成电子表格。对于其中一个必需的工作表,我需要从表格数据生成散点图。但是,散点图应包含多条连接两个点的线,因此散点图中的每个x / y系列应仅连接两个点。

通常我从openpyxl文档中发现散点图的生成方式与此小例子类似:

from openpyxl import Workbook
from openpyxl.chart import (
    ScatterChart,
    Reference,
    Series,
)

wb = Workbook()
ws = wb.active

rows = [
    ['Size', 'Batch 1', 'Batch 2'],
    [2, 40, 30],
    [3, 40, 25],
    [4, 50, 30],
    [5, 30, 25],
    [6, 25, 35],
    [7, 20, 40],
]

for row in rows:
    ws.append(row)

chart = ScatterChart()
chart.title = "Scatter Chart"
chart.style = 13
chart.x_axis.title = 'Size'
chart.y_axis.title = 'Percentage'

xvalues = Reference(ws, min_col=1, min_row=2, max_row=7)
for i in range(2, 4):
    values = Reference(ws, min_col=i, min_row=1, max_row=7)
    series = Series(values, xvalues, title_from_data=True)
    chart.series.append(series)

ws.add_chart(chart, "A10")

wb.save("scatter.xlsx")

但是,我希望在散点中连接的两个点的x(和y)坐标不在相邻的单元格中。 因此,当我通过按住'ctrl'手动导入数据系列并选择两个单元格时,我得到这样的结果:

'表$ A $ 4;!表$ A $ 6!'

而不是

'表$ A $ 4:!$ A $ 6'

拖动光标选择一系列单元格。

对于仅两个单独的不相邻单元格,这意味着我没有明确的min_row / min_col / max_row等...但只有一个单元格对列表(对于x和y)。有没有办法在openpyxl中创建一个数据系列作为单元格列表而不是连接/相邻范围?

非常感谢帮助! :)

2 个答案:

答案 0 :(得分:0)

目前没有计划支持图表系列中的非连续单元格范围。我建议你尝试安排你的数据或创建它的引用,这将允许你使用连续的范围。

答案 1 :(得分:0)

你确定这不起作用吗? 我已经修改了像你这样的情况的例子,它似乎对我有用:

from openpyxl import Workbook
from openpyxl.chart import (
    ScatterChart,
    Reference,
    Series,
)

wb = Workbook()
ws = wb.active

rows = [
    ['Size'],
    [2, 'Batch 1', 'Batch 2'],
    [3, 40, 30],
    [4, 40, 25],
    [5, 50, 30],
    [6, 30, 25],
    [7, 25, 35],
    [None, 20, 40],
]

for row in rows:
    ws.append(row)

chart = ScatterChart()
chart.title = "Scatter Chart"
chart.style = 13
chart.x_axis.title = 'Size'
chart.y_axis.title = 'Percentage'

xvalues = Reference(ws, min_col=1, min_row=2, max_row=7)
for i in range(2, 4):
    values = Reference(ws, min_col=i, min_row=2, max_row=8)
    series = Series(values, xvalues, title_from_data=True)
    chart.series.append(series)

ws.add_chart(chart, "A10")

wb.save("scatter.xlsx")

结果:

as Justin suggested in a comment