Python第三方库之openpyxl(8)
饼图
饼图将数据绘制成一个圆片,每个片代表整体的百分比。切片是按顺时针方向绘制的,0在圆的顶部。饼图只能取一组数据。该图表的标题将默认为该系列的标题。
2D饼图
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" # Cut the first slice out of the pie
slice = DataPoint(idx=0, explosion=20)
pie.series[0].data_points = [slice] ws.add_chart(pie, "D1") ws = wb.create_sheet(title="Projection") data = [
['Page', 'Views'],
['Search', 95],
['Products', 4],
['Offers', 0.5],
['Sales', 0.5],
] for row in data:
ws.append(row) projected_pie = ProjectedPieChart()
projected_pie.type = "pie"
projected_pie.splitType = "val" # split by value
labels = Reference(ws, min_col=1, min_row=2, max_row=5)
data = Reference(ws, min_col=2, min_row=1, max_row=5)
projected_pie.add_data(data, titles_from_data=True)
projected_pie.set_categories(labels) ws.add_chart(projected_pie, "A10") from copy import deepcopy
projected_bar = deepcopy(projected_pie)
projected_bar.type = "bar"
projected_bar.splitType = 'pos' # split by position ws.add_chart(projected_bar, "A27") wb.save("pie.xlsx")
运行结果
2D投影饼图
投影饼图从饼图中提取出一些切片,并将它们投射到第二个饼状图或柱状图中。当数据系列中有几个较小的项时,这是很有用的。图表可以根据百分比、val(ue)或pos(ition)进行分割。如果没有设置任何东西,应用程序就决定使用哪一个。此外,还可以定义自定义分割。
3D饼状图
from openpyxl import Workbook from openpyxl.chart import (
PieChart3D,
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 = PieChart3D()
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" ws.add_chart(pie, "D1") wb.save("pie3D.xlsx")
运行结果