使用 Openpyxl 在 Excel 中绘制饼图 - 详细教程
要使用 openpyxl 来绘制饼图,需要按照以下步骤进行操作:
- 首先,导入 openpyxl 库和相关的绘图模块:
 
from openpyxl import Workbook
from openpyxl.chart import PieChart, Reference
- 创建一个 Workbook 对象,并选择一个工作表:
 
wb = Workbook()
ws = wb.active
- 在工作表中输入数据,用于绘制饼图:
 
data = [
    ['Apple', 30],
    ['Banana', 20],
    ['Orange', 40],
    ['Grapes', 10]
]
for row in data:
    ws.append(row)
- 创建一个饼图对象,并设置相关属性:
 
chart = 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)
chart.add_data(data, titles_from_data=True)
chart.set_categories(labels)
chart.title = 'Fruit Distribution'
- 将饼图添加到工作表中的指定位置:
 
ws.add_chart(chart, 'E5')
- 保存 Workbook 对象到文件:
 
wb.save('pie_chart.xlsx')
完整的代码如下所示:
from openpyxl import Workbook
from openpyxl.chart import PieChart, Reference
wb = Workbook()
ws = wb.active
data = [
    ['Apple', 30],
    ['Banana', 20],
    ['Orange', 40],
    ['Grapes', 10]
]
for row in data:
    ws.append(row)
chart = 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)
chart.add_data(data, titles_from_data=True)
chart.set_categories(labels)
chart.title = 'Fruit Distribution'
ws.add_chart(chart, 'E5')
wb.save('pie_chart.xlsx')
运行以上代码后,会在当前目录下生成一个名为'pie_chart.xlsx'的文件,其中包含绘制好的饼图。
原文地址: https://www.cveoy.top/t/topic/lNJ5 著作权归作者所有。请勿转载和采集!