Python XlsxWriter – Pie Chart

Python XlsxWriter – Pie Chart

A pie chart represents a single data series as a circle divided into slices corresponding to each data item in the series. In a pie chart, the arc length of each slice is proportional to the quantity it represents. In the worksheet below, quarterly sales data for a product is displayed in the form of a pie chart.

Python XlsxWriter - Pie Chart

Working with Pie Charts Using XlsxWriter

To programmatically generate the above chart using XlsxWriter, first write the following data into the worksheet.

headings = ['Category', 'Values']
data = [
['Q1', 'Q2', 'Q3', 'Q4'],
[125, 60, 100, 80],
]
worksheet.write_row('A1', headings, bold)
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])

A Chart object of type pie is declared. The cell range B1:D1 is used as the value parameter of the add_series() method, and the quarters in column A (Q1, Q2, Q3, and Q4) are the categories.

chart1.add_series({
'name': 'Quarterly sales data',
'categories': ['Sheet1', 1, 0, 4, 0],
'values': ['Sheet1', 1, 1, 4, 1],
})
chart1.set_title({'name': 'Pie Chart of Quarterly Sales'})

In a pie chart, we can use the data_labels attribute to indicate the percentage value of each pie by setting percentage=True.

Example

The complete program for generating a pie chart is as follows

import xlsxwriter

wb = xlsxwriter.Workbook('hello.xlsx')
worksheet = wb.add_worksheet()

headings = ['Category', 'Values']
data = [
   ['Q1', 'Q2', 'Q3', 'Q4'],
   [125, 60, 100, 80],
]
bold=wb.add_format({'bold':True})
worksheet.write_row('A1', headings, bold)
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])

chart1 = wb.add_chart({'type': 'pie'})
chart1.add_series({
   'name': 'Quarterly sales data', 'categories': ['Sheet1', 1, 0, 4, 0],
'values': ['Sheet1', 1, 1, 4, 1],
'data_labels': {'percentage': True},
})
chart1.set_title({'name': 'Pie Chart of Quarterly Sales'})

worksheet.insert_chart('D2', chart1)

wb.close()

Output

Take a look at the pie chart produced by the above program.

Python XlsxWriter - Pie Chart

Donut Chart

Donut chart is a variation of the pie chart with a hole in the center. It displays categories as arcs rather than slices. Both make the relationship of parts to the whole easy to understand at a glance. Simply change the chart type to Doughnut.

chart1 = workbook.add_chart({'type': 'doughnut'})

A doughnut chart of the data in the above example will be displayed as follows:

Python XlsxWriter - Pie Chart

Leave a Reply

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