1####################################################################### 2# 3# An example of creating of a Pareto chart with Python and XlsxWriter. 4# 5# Copyright 2013-2021, John McNamara, jmcnamara@cpan.org 6# 7import xlsxwriter 8 9workbook = xlsxwriter.Workbook('chart_pareto.xlsx') 10worksheet = workbook.add_worksheet() 11 12# Formats used in the workbook. 13bold = workbook.add_format({'bold': True}) 14percent_format = workbook.add_format({'num_format': '0.0%'}) 15 16# Widen the columns for visibility. 17worksheet.set_column('A:A', 15) 18worksheet.set_column('B:C', 10) 19 20# Add the worksheet data that the charts will refer to. 21headings = ['Reason', 'Number', 'Percentage'] 22 23reasons = [ 24 'Traffic', 'Child care', 'Public Transport', 'Weather', 25 'Overslept', 'Emergency', 26] 27 28numbers = [60, 40, 20, 15, 10, 5] 29percents = [0.44, 0.667, 0.8, 0.9, 0.967, 1] 30 31worksheet.write_row('A1', headings, bold) 32worksheet.write_column('A2', reasons) 33worksheet.write_column('B2', numbers) 34worksheet.write_column('C2', percents, percent_format) 35 36 37# Create a new column chart. This will be the primary chart. 38column_chart = workbook.add_chart({'type': 'column'}) 39 40# Add a series. 41column_chart.add_series({ 42 'categories': '=Sheet1!$A$2:$A$7', 43 'values': '=Sheet1!$B$2:$B$7', 44}) 45 46# Add a chart title. 47column_chart.set_title({'name': 'Reasons for lateness'}) 48 49# Turn off the chart legend. 50column_chart.set_legend({'position': 'none'}) 51 52# Set the title and scale of the Y axes. Note, the secondary axis is set from 53# the primary chart. 54column_chart.set_y_axis({ 55 'name': 'Respondents (number)', 56 'min': 0, 57 'max': 120 58}) 59column_chart.set_y2_axis({'max': 1}) 60 61# Create a new line chart. This will be the secondary chart. 62line_chart = workbook.add_chart({'type': 'line'}) 63 64# Add a series, on the secondary axis. 65line_chart.add_series({ 66 'categories': '=Sheet1!$A$2:$A$7', 67 'values': '=Sheet1!$C$2:$C$7', 68 'marker': {'type': 'automatic'}, 69 'y2_axis': 1, 70}) 71 72# Combine the charts. 73column_chart.combine(line_chart) 74 75# Insert the chart into the worksheet. 76worksheet.insert_chart('F2', column_chart) 77 78workbook.close() 79