使用python-pptx的图表的图表标题

时间:2016-11-28 16:13:37

标签: python macos powerpoint python-pptx

我正在尝试为使用python-pptx库创建的powerpoint图表添加标题。我在OSX上使用Python 2.7和Python pptx版本0.6.1。

创建图表的代码如下:

df = pd.read_excel("/Users/vagabond/Documents/python_pptx_3/Bar_Charts.xlsx", sheetname=None)
f = open('/Users/vagabond/Documents/python_pptx_3/Presentation1.pptx')
prs = ppt.Presentation(f)

for sheetname, data in df.iteritems():

    slide_layout = prs.slide_layouts[9]
    slide = prs.slides.add_slide(slide_layout)

    chart_data = ppt.chart.data.XyChartData()

    series_1 = chart_data.add_series('Series 1')

    ## iterate through rows of the data frame for desired columns and add data points
    for index, row in data.iterrows():
        series_1.add_data_point(row['Share_of_apples'], row['Share_of_oranges'])

    ## define co-ordinates on the slide
    x, y, cx, cy = Inches(1), Inches(3), Inches(7), Inches(4)

    chart = slide.shapes.add_chart(
    XL_CHART_TYPE.XY_SCATTER, x, y, cx, cy, chart_data
).chart

    prs.save('scatter_charts.pptx')

现在要添加标题,我在slide.shapes.add_chart电话后添加了以下内容:

chart.has_title = True
chart.title = sheetname

如果您想知道,chart.title = sheetname中的值表名是dict df的dict键,我在第一行读到。对于每个图表,我希望分配字典中键值对的键。该程序运行没有任何错误。

问题是,它没有添加任何图表标题。

我检查了chart.chart_title是否包含任何值,它给了我一个错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-26-7cb6c1e79da2> in <module>()
      1 chart.has_title = True
      2 
----> 3 chart.chart_title.has_text_frame = True

AttributeError: 'Chart' object has no attribute 'chart_title'

1 个答案:

答案 0 :(得分:1)

python-pptx尚未对图表标题提供API支持。

您对Chart.has_title的分配没有给出错误的原因是因为Python在第一次分配时添加了该属性(因为它是一种动态语言)。该属性不在API中。

相关问题