Bhavesh Rathod
Bhavesh Rathod

Reputation: 116

Preventing overlapping labels in a pie chart Python Xlsxwriter module

Task: I am writing the dataframe/tables into excel file with the insightful charts. To write into excel file I am using xlsxwriter for adding charts and everything.

enter image description here

I have attached one sample output which currently I am getting.

Generated the pie chart from the percentages reference. For adding percentages into the excel file I have set the formulas. So I don't have any reference to the values.

I tried different configurations but I didn't get any satisfactory results.

Here, is one sample code to get the same chart with the same problem which currently I am facing. The data points are overlapping.

import xlsxwriter

# Create a workbook and add a worksheet
workbook = xlsxwriter.Workbook('pie_chart.xlsx')
worksheet = workbook.add_worksheet()

# Add the data to the worksheet
data = [84,11,2,0,2]


labels = ['A', 'B', 'C', 'D', 'E']
worksheet.write_column('A1', data)
worksheet.write_column('B1', labels)

# Create a pie chart
pie_chart = workbook.add_chart({'type': 'pie'})
pie_chart.add_series({
    'name': 'Pie Chart',
    'categories': '=Sheet1!$B$1:$B$5',
    'values': '=Sheet1!$A$1:$A$5',
    'data_labels': {'percentage': True},
})


# Insert the pie chart into the worksheet
worksheet.insert_chart('D1', pie_chart)

# # Save the workbook
workbook.close()

Current output: Current output:

Expected output: The pie chart without data points overlapping.

Upvotes: 1

Views: 303

Answers (1)

jmcnamara
jmcnamara

Reputation: 41574

Just to be clear, XlsxWriter isn't overlapping or positioning the labels, Excel is doing it when it renders the file format.

In general Excel tries to avoid overlapping labels when rendering charts but it can happen if the data segments are very small or close together. You can maybe make it a bit better by specifying leader lines and best_fit positioning. Something like this:

import xlsxwriter

# Create a workbook and add a worksheet
workbook = xlsxwriter.Workbook('pie_chart.xlsx')
worksheet = workbook.add_worksheet()

# Add the data to the worksheet
data = [84,11,2,0,2]


labels = ['A', 'B', 'C', 'D', 'E']
worksheet.write_column('A1', data)
worksheet.write_column('B1', labels)

# Create a pie chart
pie_chart = workbook.add_chart({'type': 'pie'})
pie_chart.add_series({
    #'name': 'Pie Chart',
    'categories': '=Sheet1!$B$1:$B$5',
    'values': '=Sheet1!$A$1:$A$5',
    'data_labels': {'percentage': True,
                    'leader_lines': True,
                    'position': 'best_fit'},
})


# Insert the pie chart into the worksheet
worksheet.insert_chart('D1', pie_chart)

# # Save the workbook
workbook.close()

Output:

enter image description here

In Excel it is also possible to manually position the data labels for finer grained adjustment but that isn't supported by XlsxWriter.

Upvotes: 3

Related Questions