![](/img/trans.png)
[英]How to give chart title to a chart in Python-pptx chart in Chart Area(Not the slide title)
[英]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_title
和Chart.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.