How to make labels visible inside the pie in openpyxl

Viewed 39

I automate some task with openpyxl with xlsx file, i created a piechart but i want the piechart to show the labels and not only the value ( got exemple apple, cherry… will be in text inside the pie is there a way to do that with openpyxl ?

Thanks


from openpyxl import Workbook

from openpyxl.chart import (
    PieChart,
    ProjectedPieChart,
    Reference
)
from openpyxl.chart.series import DataPoint

data = [
    ['Pie', 'Sold'],
    ['Apple', 50],
    ['Cherry', 30],
    ['Pumpkin', 10],
    ['Chocolate', 40],
]

wb = Workbook()
ws = wb.active

for row in data:
    ws.append(row)

pie = PieChart()
labels = Reference(ws, min_col=1, min_row=2, max_row=5)
data = Reference(ws, min_col=2, min_row=1, max_row=5)
pie.add_data(data, titles_from_data=True)
pie.set_categories(labels)
pie.title = "Pies sold by category"

1 Answers

Do you want to do something like this where name and percent is marked on the segments?

from openpyxl import Workbook
from openpyxl.chart.label import DataLabelList
from openpyxl.chart import (
    PieChart,
    Reference
)

data = [
    ['Pie', 'Sold'],
    ['Apple', 50],
    ['Cherry', 30],
    ['Pumpkin', 10],
    ['Chocolate', 40],
]

wb = Workbook()
ws = wb.active

for row in data:
    ws.append(row)

pie = PieChart()
labels = Reference(ws, min_col=1, min_row=2, max_row=5)
data = Reference(ws, min_col=2, min_row=1, max_row=5)
pie.add_data(data, titles_from_data=True)
pie.set_categories(labels)
pie.title = "Pies sold by category"

### Add Label into chart
pie.dataLabels = DataLabelList()
pie.dataLabels.showPercent = True
pie.dataLabels.showCatName = True

ws.add_chart(pie, "A10")

wb.save('test_chart.xlsx')

It should produce a chart like
Pie chart

Related