1、顯示圖例的簇狀柱形圖
# import import os from pptx import Presentation from pptx.util import Cm from pptx.chart.data import ChartData from pptx.enum.chart import XL_CHART_TYPE, XL_LEGEND_POSITION # 設置路徑 work_path = r'E:\pyspace\tmp\pptx' os.chdir(work_path) # 創建幻燈片 ------------------------------------------------- prs = Presentation() # 初始化 ppt 文檔 title_only_slide = prs.slide_layouts[5] slide = prs.slides.add_slide(title_only_slide) # 添加幻燈片 shapes = slide.shapes shapes.title.text = '各區銷量和收入數據' # 定義圖表數據 ------------------------------------------------- chart_data = ChartData() # 初始化 chart_data.categories = ['東區', '西區', '南區', '北區'] chart_data.add_series('銷量', (199, 214, 167, 221)) chart_data.add_series('收入', (211, 235, 188, 258)) # 將圖表添加到幻燈片 ------------------------------------------------- left, top, width, height = Cm(1), Cm(4), Cm(23), Cm(15) graphic_frame = shapes.add_chart(chart_type=XL_CHART_TYPE.COLUMN_CLUSTERED, # 圖表類型為簇狀柱形圖 x=left, y=top, # 圖表區左上角在幻燈片中的坐標位置 cx=width, cy=height, # 圖表區的長和寬 chart_data=chart_data # 圖表數據 ) # 添加圖例 ------------------------------------------------- chart= graphic_frame.chart chart.has_legend = True # 顯示圖例 chart.legend.position = XL_LEGEND_POSITION.RIGHT # 圖例顯示位置 chart.legend.include_in_layout = False # 圖例在繪圖區之外顯示 # 保存 ppt 文檔 prs.save('test.pptx')
效果: