Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-pptx formatting datalabels after adding text

As I needed to add custom text to a chart data labels in python-pptx I used

for point in plot.series[1].points:
   frame = point.data_label.text_frame
   frame.text = "Test "
   for run in frame.paragraphs[0].runs:
      run.font.size = Pt(10)
      run.font.color.rgb = RGBColor(0x0A, 0x42, 0x80)

This allowed me to change the font to the labels but I would need to rotate them. I saw the solution from This other thread but it does not work. Any ideas?

like image 860
CheshCat Avatar asked Oct 16 '25 10:10

CheshCat


1 Answers

I believe you need to change the txPr (as in the thread you mention) but on the respective element child:

for all_series in range(0, len(plot.series)):
   for i in range(0, len(plot.series[all_series]._element)):
      if re.sub("{.*}", '', plot.series[all_series]._element[i].tag) == >"dLbls":
           txPr = plot.series[all_series]._element[i].get_or_add_txPr()
           txPr.bodyPr.set('rot', '-5400000')

So you need to access the "dLbls" child within the correct element index, the "[i]" is the difference to the mentioned thread. I use regular expressions to derive the name from the ".tag"-method. There is probably a better way to find the correct index, but this is at least one ;)

This solution iterates over all series, if you do not need this you can skip the first loop (assuming you want only the 1-series):

for i in range(0, len(plot.series[1]._element)):
    if re.sub("{.*}", '', plot.series[1]._element[i].tag) == "dLbls":
        txPr = plot.series[1]._element[i].get_or_add_txPr()
        txPr.bodyPr.set('rot', '-5400000')

Note, that this only applies to data labels which were set on the single point, so e.g. through

plot.series[1].points[0].data_label.text_frame.text = "Foo"

Hopefully this helps :)

like image 119
Irgendniemand Avatar answered Oct 19 '25 01:10

Irgendniemand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!