我想使用python的pptx模块制作多个圆环图(最多3个)。目前我只能添加一个图表,如何相应地减少圆环图的大小,以便在一张幻灯片中调整2或3个图表。另外,如何根据不同数值的图表数量自动调整圆环图的大小。
Python代码:
from pptx import Presentation
from pptx.util import Pt, Cm, Inches
from pptx.chart.data import CategoryChartData, ChartData
from pptx.enum.chart import XL_CHART_TYPE
def create_ppt():
pr = Presentation()
slide1_register = pr.slide_layouts[0]
#add initial slide
slide1 = pr.slides.add_slide(slide1_register)
#top placeholder
title1 = slide1.shapes.title
#subtitle
sub_title = slide1.placeholders[1]
# insert text
title1.text = "Data"
title_para = title1.text_frame.paragraphs[0]
title_para.font.name = "Arial (Headings)"
title_para.font.size = Pt(34)
title1.top = Cm(1)
title1.left = Cm(0)
title1.width = Cm(15)
title1.height = Cm(3)
chart_data = ChartData()
chart_data.categories = ['X1', 'X2', 'X3', 'X4']
chart_data.add_series('Data 1', (75, 10, 5, 4))
x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)
chart = slide1.shapes.add_chart(
XL_CHART_TYPE.DOUGHNUT, x, y, cx, cy, chart_data
).chart
chart.has_legend = True
chart.legend.include_in_layout = False
apply_data_labels(chart)
pr.save("test222222222.pptx")
def apply_data_labels(chart):
plot = chart.plots[0]
plot.has_data_labels = True
for series in plot.series:
values = series.values
counter = 0
for point in series.points:
data_label = point.data_label
data_label.has_text_frame = True
data_label.text_frame.text = str(values[counter])
counter = counter + 1
create_ppt()
当前幻灯片:
预期输出:
1条答案
按热度按时间6ss1mwsb1#
插入图表时,您可以像以前一样指定其位置和大小:
在上面的代码中,
x
和y
是图表左上角的坐标,而cx
和cy
分别是宽度和高度。您可以重复
add_chart
调用任意次,只要您希望插入具有适当位置和大小值的图表即可。请参阅此处的
shapes.add_chart
函数文档。