简体   繁体   English

如何使用python-pptx设置圆环图数据标签的字体颜色?

[英]How to set the font color of the data labels of the doughnut chart using python-pptx?

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.任何帮助都将非常可观。

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] .正在寻找数据标签上的字体而不是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. rest 只是更明确的命名,一种同时迭代值和点的更奇特的方式,并避免重复取消引用,特别是使用相同的字体设置所有字体属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM