Open In App

Creating Charts using openpyxl

Last Updated : 04 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Charts are a powerful way to visualize data, making it easier to analyze and present information. While working with Excel files in Python, the library openpyxl comes into the picture and can be used as a tool for automating tasks like reading data, writing data, formatting cells, and of course creating charts. In this article, we will learn to create charts covering both fundamental concepts and detailed step-by-step code implementation.

What is Openpyxl?

The openpyxl is a Python library used to read and write Excel files. It provides a comprehensive API to manage Excel worksheets, including the ability to create, modify, and style cells, as well as to generate charts. Since charts are very useful for identifying trends, patterns, and insights for businesses, openpyxl is an essential tool for creating charts for data visualization. It is also useful for automating tasks related to Excel, such as generating reports or processing data in bulk.

Firstly we'll understand fundamental key concepts of openpyxl Python library and create charts using it, then we will deep dive into the code example for chart creation.

  • Workbook and Worksheet: As we know a workbook is an Excel file, and a worksheet is basically a single sheet within a workbook file. In the Python library openpyxl, we need to create a new workbook or open an existing workbook and we should select the worksheet within the workbook, where we can add the chart.
  • Chart Types: The Python library openpyxl can support various charts like Line chart, Bar Chart, Scatter Chart, Pie chart, etc. Each and every chart helps us in different situation and serves different purposes depending on the nature of data we have.
  • Chart Data Series: A chart is usually comprised of one or more data series, out of which each series represents a collection of related data points that are plotted on the chart.
  • Chart Axes: As we know, charts often have two two axes X-axis (horizontal) and the Y-axis (vertical), these axes are used to map the data series to the chart area.
  • Anchoring the Chart: The charts must be positioned within the worksheet in our workbook. This can be done by specifying the cell where the top left corner of the chart should be anchored.

Creating Charts using openpyxl

Let us see a step-by-step process to create charts using openpyxl in Python.

Intall 'openpyxl'

If openpyxl is not already installed in ourr system, we can install it by using the following command in the command line or terminal. Use pip if the OS is Windows, and pip3 if the OS is Mac or Linux.

pip/pip3 install openpyxl

Import Necessary Modules

Next, import the necessary modules from the openpyxl python library such as Workbook, Bar Chart, etc.

Python
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference

Create a Workbook and Add Data

Now create a new or load an existing workbook and add sample data to the worksheet.

Python
wb = Workbook()
ws = wb.active

data = [
    ["Year", "Sales"],
    [2020, 300],
    [2021, 400],
    [2022, 350],
    [2023, 500],
]

for row in data:
    ws.append(row)

Create a Basic Chart

In this step, we will create a basic chart using the Class 'BarChart', then define the data series and categories, now add the chart to the worksheet.

Python
chart = BarChart()
data = Reference(ws, min_col=2, min_row=1, max_row=5)
categories = Reference(ws, min_col=1, min_row=2, max_row=5)

chart.add_data(data, titles_from_data=True)
chart.set_categories(categories)
ws.add_chart(chart, "E5")

Save the Workbook

In this final step, save the workbook to an Excel File.

Python
# ...

wb.save("sales_chart.xlsx")


Creating Charts

Let us see a few different examples, to see how we can create charts using openpyxl.

1. Bar Graph

In this example, we will create a bar graph using openpyxl library. The bar chart will be created using the BarChart() function.

Python
# import necessary library
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference

# Create a new Workbook
wb = Workbook()
ws = wb.active

# Add data to the worksheet
data = [
    ["Year", "Sales"],
    [2020, 300],
    [2021, 400],
    [2022, 350],
    [2023, 500],
]

for row in data:
    ws.append(row)

# Create a BarChart object
chart = BarChart()

# Define the data (sales values) for the chart
data = Reference(ws, min_col=2, min_row=1, max_row=5)

# Define the categories (years)
categories = Reference(ws, min_col=1, min_row=2, max_row=5)

# Add data and categories to the chart
chart.add_data(data, titles_from_data=True)
chart.set_categories(categories)

# Add the chart to the worksheet
ws.add_chart(chart, "E5")

# Save the Workbook to a file
wb.save("sales_chart.xlsx")

Output:

Bar Chart using openpyxl
Bar Chart using openpyxl

2. Line Chart

In this example, we will create a Line chart using the LineChart() function.

Python
from openpyxl import Workbook
from openpyxl.chart import LineChart, Reference

# Create a new Workbook
wb = Workbook()
ws = wb.active

# Add data to the worksheet
data = [
    ["Year", "Sales"],
    [2020, 300],
    [2021, 400],
    [2022, 350],
    [2023, 500],
]

for row in data:
    ws.append(row)

# Create a LineChart object
chart = LineChart()

# Define the data (sales values) for the chart
data = Reference(ws, min_col=2, min_row=1, max_row=5)

# Define the categories (years)
categories = Reference(ws, min_col=1, min_row=2, max_row=5)

# Add data and categories to the chart
chart.add_data(data, titles_from_data=True)
chart.set_categories(categories)

# Add the chart to the worksheet
ws.add_chart(chart, "E5")

# Save the Workbook to a file
wb.save("sales_line_chart.xlsx")

Output:

Line Chart using openpyxl
Line Chart using openpyxl

3. Scattered Chart

In this example, we will create a Scatter Chart using the ScatterChart() function.

Python
from openpyxl import Workbook
from openpyxl.chart import ScatterChart, Reference, Series

# Create a new Workbook
wb = Workbook()
ws = wb.active

# Add data to the worksheet
data = [
    ["X", "Y1", "Y2"],
    [1, 10, 20],
    [2, 20, 30],
    [3, 30, 40],
    [4, 40, 50],
    [5, 50, 60],
]

for row in data:
    ws.append(row)

# Create a ScatterChart object
chart = ScatterChart()
chart.title = "Scatter Chart Example"
chart.style = 13
chart.x_axis.title = 'X Axis'
chart.y_axis.title = 'Y Axis'

# Define the X and Y data for the first series
x_values = Reference(ws, min_col=1, min_row=2, max_row=6)
y_values = Reference(ws, min_col=2, min_row=2, max_row=6)
series1 = Series(y_values, x_values, title="Y1 Series")

# Define the Y data for the second series
y_values2 = Reference(ws, min_col=3, min_row=2, max_row=6)
series2 = Series(y_values2, x_values, title="Y2 Series")

# Add the series to the chart
chart.series.append(series1)
chart.series.append(series2)

# Add the chart to the worksheet
ws.add_chart(chart, "E5")

# Save the Workbook to a file
wb.save("scatter_chart.xlsx")

Output:

Scatter Chart using openpyxl
Scatter Chart using openpyxl

4. Pie Chart

In this example, we will create a Pie Chart using the PieChart() function.

Python
from openpyxl import Workbook
from openpyxl.chart import PieChart, Reference

# Create a new Workbook
wb = Workbook()
ws = wb.active

# Add data to the worksheet
data = [
    ["Category", "Value"],
    ["A", 40],
    ["B", 30],
    ["C", 20],
    ["D", 10],
]

for row in data:
    ws.append(row)

# Create a PieChart object
chart = PieChart()

# Define the data (values) for the chart
data = Reference(ws, min_col=2, min_row=2, max_row=5)

# Define the categories (labels)
categories = Reference(ws, min_col=1, min_row=2, max_row=5)

# Add data and categories to the chart
chart.add_data(data, titles_from_data=True)
chart.set_categories(categories)

# Add the chart to the worksheet
ws.add_chart(chart, "E5")

# Save the Workbook to a file
wb.save("category_pie_chart.xlsx")

Output:

Pie Chart using openpyxl
Pie Chart using openpyxl

Conclusion

Creating charts using openpyxl in Python is a straightforward process that allows for dynamic data visualization within Excel files. Whether we need bar charts, line charts, or other types of charts, openpyxl provides the tools necessary to automate and customize our Excel-based reports. With these examples, we should be well-equipped to start integrating charts into our own Excel projects.


Next Article
Practice Tags :

Similar Reads