Reputation: 3019
I'm looking for a way to access positions of individual bar charts created by python-pptx library. I assume individual bars are considered 'shapes' and do have properties of left, top, width, height. I've already managed to create charts using code below.
How can individual bars in the chart be referenced, and their properties be accessed, as I need to do more sophisticated charts i.e. with arrows between bars showing year-on-year growth etc.
Thanks.
# CHART
chart_data = ChartData()
chart_data.categories = ['January', 'February', 'March', 'April']
chart_data.add_series('Revenue', monthly_revenue, 3)
chart_data.add_series('Cost', monthly_cost, 3)
graphic_frame = s.placeholders[10].insert_chart(XL_CHART_TYPE.COLUMN_CLUSTERED, chart_data)
chart = graphic_frame.chart
plot = chart.plots[0]
plot.has_data_labels = True
plot.overlap = -10
data_labels = plot.data_labels
data_labels.font.size = Pt(11)
data_labels.font.color.rgb = RGBColor(0,0,0)
data_labels.number_format = "#,##0"
chart.value_axis.has_minor_gridlines = False
chart.value_axis.has_major_gridlines = False
chart.value_axis.tick_labels.font.size = Pt(12)
chart.value_axis.tick_labels.number_format = "#,##0"
chart.category_axis.tick_labels.font.size = Pt(12)
chart.series[1].fill.solid()
chart.series[1].fill.fore_color.rgb = RGBColor(192,80,77)
Upvotes: 1
Views: 1300
Reputation: 28933
Bars in a chart do not have individual position and size information, at least not stored in the XML of the .pptx file.
So the short answer is you can't directly do what you're asking for using python-pptx.
The MS API, accessible using VBA for example, but also with Iron Python, does provide a Point.left, .top, .width, and .height. So you might be able do something in that environment if you're able to endure the hardships :) Note that code like that is directly manipulating a PowerPoint application instance and only in Windows if I'm not mistaken. So there are pretty big problems with that if you're trying to run it server side.
The elements of a chart, such as bars, are not shapes. The entire chart is a self-contained object contained in a so-called "graphics frame" shape, as is a table. The chart itself is a DrawingML object (as opposed to a PresentationML object), an XML vocabulary shared between Word, Excel, and PowerPoint. That's why you can transplant a chart between those three. Anyway, maybe more background than you wanted, but short story is they are handled very differently than say a rectangle shape which very definitely does have an explicit position and size.
Upvotes: 3