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

孤街浪徒 提交于 2019-12-05 02:20:27

问题


Suppose that we have this code:

  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")

How can i plot second column values to same line-chart? (and add legend)?


回答1:


I rearranged your code, slightly, so that the chart and its properties are declared before the series are created. Then, it's simply a matter of repeating your series creation on the second range of values. As far as I know, unless I'm misunderstanding the question, Excel creates the legend automatically.

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")


来源:https://stackoverflow.com/questions/30002482/how-we-can-draw-two-series-of-data-in-openpyxl-package-of-python-line-chart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!