1 添加图表
图表是展示数据的有效方式,Python-PPTX库支持多种图表类型,如折线图、柱状图、饼图等。本节将介绍如何使用Python-PPTX库创建和修改图表。
1.1 创建柱状图
柱状图是最常见的图表类型之一,适用于对比多个分类数据。下面是创建柱状图的步骤:
from pptx import Presentation
from pptx.enum.chart import XL_CHART_TYPE
from pptx.util import Inches
from pptx.enum.chart import XL_LEGEND_POSITION, XL_LABEL_POSITION
from pptx.chart.data import CategoryChartData
# 创建一个演示文稿对象
prs = Presentation()
# 添加一个空白幻灯片
slide_layout = prs.slide_layouts[6] # 空白布局
slide = prs.slides.add_slide(slide_layout)
# 创建图表数据
chart_data = CategoryChartData()
chart_data.categories = ['第一季度', '第二季度', '第三季度', '第四季度']
chart_data.add_series('销售额', (19.2, 21.4, 16.7, 23.5))
# 添加柱状图
x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)
chart = slide.shapes.add_chart(
XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data
).chart
# 设置图表样式
chart.has_legend = True
chart.legend.position = XL_LEGEND_POSITION.BOTTOM
chart.legend.include_in_layout = False
# 设置数据标签
chart.plots[0].has_data_labels = True
chart.plots[0].data_labels.show_value = True
chart.plots[0].data_labels.position = XL_LABEL_POSITION.OUTSIDE_END
# 保存演示文稿
prs.save('advanced_content.pptx')
在上面的代码中:
- 使用
CategoryChartData
创建了图表数据,设置分类和系列数据。 - 使用
add_chart()
方法在幻灯片中添加一个簇状柱形图。 - 通过
chart
对象的属性设置图例和数据标签的显示样式。
1.2 修改图表样式
Python-PPTX提供了丰富的API来修改图表样式,包括图表类型、颜色、网格线等。
# 修改图表类型
chart.chart_type = XL_CHART_TYPE.LINE_MARKERS # 更改为折线图
# 修改系列的颜色
series = chart.series[0]
series.format.fill.solid()
series.format.fill.fore_color.rgb = RGBColor(0xFF, 0x00, 0x00) # 红色填充
# 添加和修改网格线
chart.value_axis.major_gridlines.format.line.color.rgb = RGBColor(0xC0, 0xC0, 0xC0) # 设置网格线颜色
chart.value_axis.has_minor_gridlines = True # 显示次要网格线
在这里:
- 使用
chart_type
属性更改图表类型为折线图。 series.format.fill
用于修改系列的填充颜色。- 通过
value_axis
对象修改网格线样式。
1.3 创建饼图
饼图用于显示分类数据占比,适合展示数据的比例关系。
from pptx.enum.chart import XL_LEGEND_POSITION, XL_LABEL_POSITION
from pptx.chart.data import CategoryChartData
# 创建饼图数据
chart_data = CategoryChartData()
chart_data.categories = ['第一季度', '第二季度', '第三季度', '第四季度']
chart_data.add_series('市场份额', (40, 30, 20, 10))
# 添加饼图
x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)
chart = slide.shapes.add_chart(
XL_CHART_TYPE.PIE, x, y, cx, cy, chart_data
).chart
# 设置饼图样式
chart.has_legend = True
chart.legend.position = XL_LEGEND_POSITION.RIGHT
# 设置数据标签
chart.plots[0].has_data_labels = True
data_labels = chart.plots[0].data_labels
data_labels.number_format = '0%'
data_labels.position = XL_LABEL_POSITION.OUTSIDE_END
# 保存演示文稿
prs.save('advanced_content_with_pie_chart.pptx')
在上面的代码中:
- 使用
add_chart()
方法添加了一个饼图。 - 设置图例位置为右侧,数据标签显示为百分比格式。
1.4 自定义图表轴和标签
图表的轴和标签是展示数据的重要部分,您可以根据需求自定义这些元素。
# 修改X轴和Y轴
chart.category_axis.has_major_gridlines = True
chart.category_axis.major_tick_mark = XL_TICK_MARK.OUTSIDE
chart.value_axis.maximum_scale = 30.0 # 设置Y轴的最大值
chart.value_axis.minimum_scale = 10.0 # 设置Y轴的最小值
chart.value_axis.has_minor_gridlines = True # 显示次要网格线
此代码设置了X轴的网格线和刻度线,以及Y轴的最大值、最小值和次要网格线的显示。
本节主要介绍了如何使用Python-PPTX库创建和自定义各种类型的图表,包括柱状图、折线图和饼图。