首页 > 解决方案 > 如何在循环中给图表一个带有迭代器值的标题?

问题描述

我想titles在一个循环中为我的每个图表添加一个标题(来自一个列表),但是当我尝试向图表添加一个文本框(使用迭代器)时循环失败。是否允许迭代器值用作图表的标题?我正在使用 Python 3.6。有任何想法吗?

cleaned = [['AF In', 0.281777948141098],  ['AF Top', 0.11941492557525635],  ['AF View', 12.46446630278714],  ['AF  Non',   'AF V', 0.6745020151138306, 0.6817344427108765],  ['AF Cab',   'AF N',   'AF HB', 0.6878681182861328, 0.2603790760040283, 0.05175277590751648]]

titles = ['first', 'second', 'third', 'fourth', 'fifth']

from pptx import Presentation
from pptx.chart.data import ChartData
from pptx.chart.data import XyChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.util import Inches,Pt
from pptx.enum.chart import XL_LABEL_POSITION
from pptx.dml.color import RGBColor
from pptx.dml import fill
from pptx.chart.chart import ChartTitle
from pptx.chart.chart import Chart

# create presentation
prs = Presentation()

#For each list items from query_results (cleaned)
for idx, (chart_result, t) in enumerate(zip(cleaned, titles)):
    #define size of chart
    x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)

    try:

        #split the results into two arrays
        arr1, arr2 = np.array_split(chart_result,2)
        #create a table for chart data
        chart_data = CategoryChartData()
        #assign arr1 to categories
        chart_data.categories = arr1
        #assign arr2 to series
        chart_data.add_series('series_1',(float(x) for x in arr2))

        #add slide
        prs.slides.add_slide(prs.slide_layouts[6])
        #add chart to slide by index
        prs.slides[idx].shapes.add_chart(XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data)
        #chart = shapes[0].chart
        chart.chart_title.text_frame.text = t

    except:
        print(f'chart load failed {idx}')

标签: python-3.xpython-pptx

解决方案


确保您确实引用了图表对象;我没有在您的代码中看到可以提供给您的行。我建议:

chart = prs.slides[idx].shapes.add_chart(...).chart

返回的对象.add_chart()是图形框架形状。此形状包含使用.chart属性获得的图表。

那么你在 try 块最后一行的赋值应该会成功。


推荐阅读