繁体   English   中英

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

[英]Chart Title for Chart using 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中的值 sheetname 是我在第一行中读取的 dict df 的字典键。 对于每个图表,我都希望分配字典中键值对的键。 程序运行没有任何错误。

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

我检查了 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'

更新Chart.chart_titleChart.has_title已添加到python-pptx因为这个问题的原始答案: https : Chart.chart_title 。 chart.Chart.chart_title


python-pptx还没有对图表标题的 API 支持。

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

以下代码行将起作用:

chart.chart.chart_title.text_frame.clear

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM