使用python-pptx设置图表间隙宽度无效的问题排查
解决python-pptx设置BAR_CLUSTERED图表gap_width无效的问题
我用python-pptx创建BAR_CLUSTERED类型图表时,设置gap_width为0%,但生成的图表仍保持默认150%的间隙宽度,尝试了多种写法都无效。
相关代码:
import openpyxl from pptx import Presentation from pptx.chart.data import CategoryChartData from pptx.enum.chart import XL_CHART_TYPE from pptx.util import Cm from pptx.dml.color import RGBColor # 设置文件路径 pptx_path = r"C:\Users\user\Desktop\test_pptx\3_slide_pattern.ppt" excel_files = [ r"C:\Users\user\Desktop\test_pptx\072022.xlsx", r"C:\Users\user\Desktop\test_pptx\082022.xlsx", r"C:\Users\user\Desktop\test_pptx\092022.xlsx", ] # 读取Excel文件中的数据 data = [] for file in excel_files: wb = openpyxl.load_workbook(file) ws = wb['Sheet1'] product_name = ws['B5'].value production = ws['D5'].value / 1000 deviation = ws['F5'].value data.append((product_name, production, deviation)) # 打开现有演示文稿并选择第一张幻灯片 prs = Presentation(pptx_path) slide = prs.slides[0] chart_data = CategoryChartData() chart_data.categories = [item[0] for item in data] chart_data.add_series('Выпуск продукции', [item[1] for item in data]) # 将图表类型改为水平簇状条形图 chart = slide.shapes.add_chart( XL_CHART_TYPE.BAR_CLUSTERED, Cm(12.69), Cm(3.78), Cm(8), Cm(2), chart_data ).chart chart.series[0].gap_width = 0 # 设置图表样式 bar_colors = [RGBColor(124, 158, 130), RGBColor(66, 116, 75), RGBColor(24, 85, 35)] for i, point in enumerate(chart.series[0].points): point.format.fill.solid() point.format.fill.fore_color.rgb = bar_colors[i] point.data_label.text_frame.text = f"{data[i][1]:.0f}" point.data_label.text_frame.paragraphs[0].runs[0].font.color.rgb = RGBColor(105, 109, 111) # 删除图表标题、网格线和坐标轴 chart.has_title = False chart.value_axis.has_major_gridlines = False chart.value_axis.visible = False chart.category_axis.visible = False # 保存演示文稿 prs.save(r"C:\Users\user\Desktop\test_pptx\3_slide_complete.pptx") print("готово")
已尝试的两种写法:
chart.series[0].overlap = 100 chart.series[0].gap_width = 0
以及:
chart.gap_width = 0
问题原因与解决方案
在python-pptx中,簇状条形图的间隙宽度(gap_width)是图表的Plot对象属性,而非Chart或Series对象的属性。之前的写法都找错了属性层级。
正确的修改方式是:
将代码中的chart.series[0].gap_width = 0替换为:
# 针对BAR_CLUSTERED类型,取第一个plot对象设置gap_width chart.plots[0].gap_width = 0
如果是多系列的簇状图,若需要调整同类别内系列的重叠度,可同时设置overlap属性:
chart.plots[0].overlap = 100 # 同类别系列完全重叠 chart.plots[0].gap_width = 0 # 类别间无间隙
修改后重新运行代码,生成的PPT图表就会显示0%的间隙宽度。
内容的提问来源于stack exchange,提问作者Haxsokol Sokol
相关产品推荐
相关产品推荐

