Reputation: 81
I am trying to format the doughnut chart using the below code. It's doing everything except changing the color of data labels.
d_plot = chart.plots[0]
d_plot.has_data_labels = True
for series in d_plot.series:
values = series.values
counter = 0
for point in series.points:
ddl = point.data_label
ddl.has_text_frame = True
ddl.text_frame.text = str("{:.0%}".format(values[counter]))
ddl.text_frame.paragraphs[0].font.name = "calibri"
ddl.text_frame.paragraphs[0].font.size = Pt(9)
ddl.font.color.rgb = RGBColor(255, 0, 0)
counter = counter + 1`
Is there a way to achieve that? Any help will highly appreciable.
Upvotes: 1
Views: 975
Reputation: 29021
Give this a try:
plot = chart.plots[0]
plot.has_data_labels = True
for series in plot.series:
for point, value in zip(series.points, series.values):
data_label = point.data_label
data_label.has_text_frame = True
text_frame = data_label.text_frame
text_frame.text = str("{:.0%}".format(value))
font = text_frame.paragraphs[0].runs[0].font
font.name = "Calibri"
font.size = Pt(9)
font.color.rgb = RGBColor(255, 0, 0)
The main difference I saw was your second-to-last line:
ddl.font.color.rgb = RGBColor(255, 0, 0)
Which is looking for a font on the data-label rather than data_label.text_frame.paragraphs[0]
. Once you set an attribute on the font on the paragraph it's going to override any font defined higher up. Since I don't suppose you're concerned about inheriting any font characteristics, I went ahead and set them all at the run level, which overrides anything defined higher up in the style hierarchy.
The rest is just more explicit naming, a fancier way of iterating through values and points at the same time, and avoiding repeated dereferencing, in particular using the same font for setting all the font properties.
Upvotes: 2