Skip to content
Home » openpyxl Part 20 – Pie Charts

openpyxl Part 20 – Pie Charts

Spread the love

In the previous part we created a line chart. In this part we’ll create pie charts. We’ll be using the wb4.xlsx workbook to start with. As you remember, it contains random data:

20152016201720182019
tables13431113113917611827
closets15721492163710671824
chairs10971752199115121587

As the data is random, your data is different if you were following along. Here’s the line chart we generated for the data:

line chart

It actually sits on top of the bar chart that we created even before:

bar chart

In this article we’ll create a pie chart that will represent the sales of the three products in 2015. Let’s start by loading the workbook:

>>> from openpyxl import load_workbook
>>> workbook = load_workbook(filename="wb4.xlsx")
>>> sheet = workbook.active

Now we need the PieChart and Reference classes:

>>> from openpyxl.chart import PieChart, Reference

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Let’s create the chart and the references:

>>> chart = PieChart()
>>> data = Reference(worksheet=sheet, min_col=2, min_row=1, max_row=4) 
>>> labels = Reference(worksheet=sheet, min_col=1, min_row=2, max_row=4)

Let’s set the title, add the data to the chart and set the categories:

>>> chart.title = '2015 Sales'
>>> chart.add_data(data, titles_from_data=True)
>>> chart.set_categories(labels)

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Finally let’s add the chart and save the workbook as a new file:

>>> sheet.add_chart(chart, 'N10')
>>> workbook.save("wb4b.xlsx")

If you now open the new file, you will see the pie chart next to the line chart we created before:

pie charts

There are lots of other charts that you can create. Some of the fanciest ones are 3D charts. We’ll have a look at some in the next part of the openpyxl series.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love
Tags:

Leave a Reply