In the previous parts of the series we created a bar chart, a line chart and a pie chart. There are lots of other chart types, so if you’re interested, you should check it out in the documentation. In this article, which is the last in my openpyxl series, I’d like to demonstrate an example of a 3D chart. There are several types of 3D charts like 3D line chart, 3D bar chart, 3D area chart or 3D pie chart. I’m going to discuss just one of them, the 3D Line chart. I’ll be using the wb4.xlsx file where we added a 2D line chart. It contains the following 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 |
The data is random, so your data is different if you were following along. Here’s the line chart we generated for the data:
We’ll place the 3D chart next to the 2D one. So, let’s load our workbook:
>>> from openpyxl import load_workbook
>>> workbook = load_workbook(filename="wb4.xlsx")
>>> sheet = workbook.active
Let’s import the classes we need:
>>> from openpyxl.chart import LineChart3D, Reference
Let’s create the chart and the references:
>>> chart = LineChart3D()
>>> data = Reference(worksheet=sheet, min_row=1, max_row=4, min_col=2, max_col=6)
>>> titles = Reference(worksheet=sheet, min_row=2, max_row=4, min_col=1)
Now we can set the title, add the data to the chart, set the categories and the titles of the X and Y axes:
>>> chart.title = 'Furniture Sales'
>>> chart.add_data(data, titles_from_data=True)
>>> chart.set_categories(titles)
>>> chart.x_axis.title = 'Products'
>>> chart.y_axis.title = 'Sales'
Finally, let’s add the chart and save the file:
>>> sheet.add_chart(chart, 'N10')
>>> workbook.save("wb4c.xlsx")
If you now open the file, you will see the two charts, 2D and 3D, side by side:
That’s it as far as adding charts to spreadsheets is concerned in our openpyxl series. And that’s it as far as the whole openpyxl series is concerned. There’s lot of stuff that I didn’t even touch upon, so feel free to explore the openpyxl module.