python-3.x - 如何在循环中给图表一个带有迭代器值的标题?
问题描述
我想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}')
解决方案
确保您确实引用了图表对象;我没有在您的代码中看到可以提供给您的行。我建议:
chart = prs.slides[idx].shapes.add_chart(...).chart
返回的对象.add_chart()
是图形框架形状。此形状包含使用.chart
属性获得的图表。
那么你在 try 块最后一行的赋值应该会成功。
推荐阅读
- python - 具有自定义转换器类的管道在使用 Featureunion 的完整管道中不起作用
- r - 从 Ubuntu 16.04 访问 RPlumber API 时出现“异常”
- python - 在分类案例研究中识别冗余列/变量
- keras - Keras softmax 层返回 one-hot 编码数组
- angular - 如何在不丢失活跃订阅者的情况下更新 Observable?
- javascript - HTML IFrame 不允许下载文件
- arrays - Spring Annotations - 使用数组属性配置
- java - Java 概念 后期版格式化部分
- javascript - 将字符串数组转换为一个对象,其中最内层的子对象是 JavaScript/Typescript 中的空数组
- nunjucks - NUNJUCKS 设置变量