我们如何在 python 的 "openpyxl" 包中绘制两个系列的数据(折线图)

How we can draw two series of data in "openpyxl" package of python (line-chart)

假设我们有这样的代码:

  from openpyxl import Workbook
    wb = Workbook()
    ws = wb.active

    for row in range(1,10):
            value = ws.cell(row=row,column=1).value = row+5

    for row in range(1,10):
            value2 = ws.cell(row=row,column=2).value = row

    wb.save("SampleChart.xlsx")
    from openpyxl.charts import Reference, Series,LineChart

    values = Reference(ws, (1, 1), (9, 1))
    series = Series(values, title="First series of values")
    chart = LineChart()
    chart.append(series)
    chart.drawing.name = 'This is my chart'
    ws.add_chart(chart)
    wb.save("SampleChart.xlsx")

如何将第二列值绘制到同一折线图中? (并添加 legend)?

我稍微重新安排了您的代码,以便在创建系列之前声明图表及其属性。然后,只需在第二个值范围内重复您的系列创建即可。据我所知,除非我误解了这个问题,Excel 会自动创建图例。

from openpyxl import Workbook
wb = Workbook()
ws = wb.active

for row in range(1,10):
        value = ws.cell(row=row,column=1).value = row+5

for row in range(1,10):
        value2 = ws.cell(row=row,column=2).value = row

wb.save("SampleChart.xlsx")

from openpyxl.charts import Reference, Series,LineChart

# setup the chart
chart = LineChart()
chart.drawing.name = 'This is my chart'

# setup and append the first series
values = Reference(ws, (1, 1), (9, 1))
series = Series(values, title="First series of values")
chart.append(series)

# setup and append the second series
values = Reference(ws, (1, 2), (9, 2))
series = Series(values, title="Second series of values")
chart.append(series)

ws.add_chart(chart)
wb.save("SampleChart.xlsx")