Creating a line chart using Openpyxl in Python

In this tutorial, we will learn how to draw line charts using openpyxl in Python. Python provides openpyxl library using which we can perform operations like reading, writing, and modifying data in excel sheets. This library has different charts like bar charts, line charts, area charts, etc.

Step-by-step process:

  • Creating chart object of chart class.
  • Insert data in it.
  • Add the chart object to the sheet object.

Check: How to install openpyxl in Python

Plotting line chart in Openpyxl

To plot a line chart, we are using LineChart class from openpyxl.chart submodule. Next, create a spreadsheet and insert data into it and lastly, add this chart object to the sheet object. Let us consider an example,

Example:

import openpyxl
from openpyxl.chart import LineChart, Reference
wb = openpyxl.Workbook()
sheet = wb.active
for i in range(1, 20, 2):
    sheet.append([i])
values = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 10)
chart = LineChart()
chart.add_data(values)
chart.title = "LINE-CHART"
chart.x_axis.title = "X-AXIS"
chart.y_axis.title = "Y-AXIS"
sheet.add_chart(chart, "E2")
wb.save("lchart.xlsx")

Output:

Plotting line chart in Openpyxl

From the above image, we can see that the line chart is added to the sheet at cell “E2” using add_chart() method.

 

Plotting 3D line chart

To plot a 3D line chart, we are using LineChart3D class from openpyxl.chart submodule.

Example:

import openpyxl
from openpyxl.chart import LineChart3D, Reference
wb = openpyxl.Workbook()
sheet = wb.active
for i in range(1, 20, 2):
    sheet.append([i])
values = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 10)
chart = LineChart3D()
chart.add_data(values)
chart.title = "LINE-CHART3D"
chart.x_axis.title = "X-AXIS"
chart.y_axis.title = "Y-AXIS"
sheet.add_chart(chart, "E2")
wb.save("lchart3d.xlsx")

Output:

How to create a line chart using Openpyxl in Python

From the above image, we can see that the 3D line chart is added to the sheet at cell “E2” using add_chart() method.

You may also learn,

Leave a Reply

Your email address will not be published. Required fields are marked *