`您好,我正在尝试使用 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")
#我试图修改 min_row/col 和 max_row/col 但我没有设法得到解决方案。`
以简单的形式将数据添加为一个系列;
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')