I would like to be able to flexibly show or hide data labels in a stacked bar chart.
I thought this would have been possible by accessing an individual datalabel as such:
plot.series[0].points[1].data_label
and then assigning its has_text_frame
attribute to True
or False
, but this isn't working.
My use case is more complex than the below, but was trying to get it work with a simple example. If possible please show me how it can be done with the code snippet attached below.
from pptx import Presentation
from pptx.chart.data import ChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.util import Cm
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[5])
x = ['one','two','three', 'four']
y = [7.0, 5.0, 4.0, 2.0]
specs = {
'height': Cm(7.82),
'width': Cm(14.8),
'left': Cm(2.53),
'top': Cm(5.72)}
data = ChartData()
data.categories = x
label_values = tuple(y)
data.add_series('Series 1', label_values)
frame = slide.shapes.add_chart(XL_CHART_TYPE.BAR_CLUSTERED, specs['left'],
specs['top'], specs['width'],
specs['height'], data)
chart = frame.chart
plot = chart.plots[0]
# Attempt at showing all labels except for one
plot.has_data_labels = True
plot.series[0].points[1].data_label.has_text_frame =False
prs.save('chart-01.pptx')
I think the approach you want is to turn them on individually rather than to turn them off individually. I believe PowerPoint supports both approaches, but python-pptx
will only support the "add" method, if it does that.
Try something like this:
plot = chart.plots[0]
# ---best if data-labels don't appear by default
# ---turn them off, but only if they already show
# ---since it might disrupt what comes next
# plot.has_data_labels = False
plot.series[0].points[0].data_label.text_frame.text = "Foo"