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:
2015 | 2016 | 2017 | 2018 | 2019 | |
tables | 1343 | 1113 | 1139 | 1761 | 1827 |
closets | 1572 | 1492 | 1637 | 1067 | 1824 |
chairs | 1097 | 1752 | 1991 | 1512 | 1587 |
As the data is random, your data is different if you were following along. Here’s the line chart we generated for the data:
It actually sits on top of the bar chart that we created even before:
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
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)
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:
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.