如何使用 Openpyxl 在 Excel 中制作包含行数据的饼图?

问题描述 投票:0回答:1

`您好,我正在尝试使用 openpyxl 制作包含行数据的饼图。我发现了几个列数据的例子,但我需要行数据。例子是这个:


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

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

wb = Workbook()
ws = wb.active

for row in data:
    ws.append(row)

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

#我得到的结果如图所示Picture

#我试图修改 min_row/col 和 max_row/col 但我没有设法得到解决方案。`

python excel openpyxl
1个回答
0
投票

以简单的形式将数据添加为一个系列;

from openpyxl import Workbook
from openpyxl.chart import (
    PieChart,
    ProjectedPieChart,
    Series,  # <-- Add Series
    Reference
)
from openpyxl.chart.series import DataPoint

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

]

wb = Workbook()
ws = wb.active

for row in data:
    ws.append(row)

pie = PieChart()
labels = Reference(ws, min_col=2, min_row=1, max_col=5, max_row=1)
# data = Reference(ws, min_col=2, min_row=2, max_col=5, max_row=2)
### Expand range for label
data = Reference(ws, min_col=1, min_row=2, max_col=5, max_row=2)

# Add chart Series
# pie.add_data(data, titles_from_data=True)
series = Series(data, title_from_data=True)
pie.append(series)


pie.set_categories(labels)
pie.title = "Pies sold by category"
ws.add_chart(pie, "D1")

wb.save('pie_chart.xlsx')
© www.soinside.com 2019 - 2024. All rights reserved.