How can we make two series of data in python openpyxl package (line chart)
Let's assume 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 map the values of the second column to the same line chart? (and add legend
)?
+3
source to share
1 answer
I modified your code a little so that the chart and its properties are declared before the series is created. Then it's just a matter of repeating the creation of your series in a second range of values. As far as I know, if I am not mistaken in the question, Excel automatically generates the legend.
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")
+4
source to share