我有一个图表占位符,我在其中插入了chart_type' DONUT'的图表。我已经为其添加了数据标签,并希望更改其位置。出于某种原因,文档中给出的方法对我的图表没有影响。
这是我的代码,如果我做错了,请帮忙 -
from pptx import Presentation
from pptx.chart.data import ChartData
from pptx.enum.chart import XL_CHART_TYPE, XL_LABEL_POSITION, XL_DATA_LABEL_POSITION, XL_TICK_MARK, XL_TICK_LABEL_POSITION
chart_data = ChartData()
chart_data.add_series('', tuple(input_chart_data[x] for x in input_chart_data))
graphic_frame = content_placeholder.insert_chart(XL_CHART_TYPE.DOUGHNUT, chart_data)
chart = graphic_frame.chart
chart.has_legend = False
#Adding Data-Labels with custom text
chart.plots[0].has_data_labels = True
data_labels = chart.plots[0].data_labels
i = 0
series = chart.series[0]
for point in series.points:
fill = point.format.fill
fill.solid()
fill.fore_color.rgb = RGBColor(<color_code>)
point.data_label.has_text_frame = True
#Assigning custom text for data label associated with each data-point
point.data_label.text_frame.text = str(chart_data.categories[i].label) + "\n" + str(float(chart.series[0].values[i])) + "%"
for run in point.data_label.text_frame.paragraphs[0].runs:
run.font.size = Pt(10)
i+=1
data_labels.position = XL_LABEL_POSITION.OUTSIDE_END
答案 0 :(得分:2)
PowerPoint对于您放置某些图表属性的位置非常挑剔,并且可以随时忽略它们(尽管它始终如此)。
值得尝试的快速选项是在系列中逐个点地设置值。如下所示:
for point in series.points:
point.data_label.position = XL_LABEL_POSITION.OUTSIDE_END
最可靠的方法是首先在示例图表上使用PowerPoint本身手动生成您想要的效果,然后使用opc-diag
检查保存文件中的XML PowerPoint生成。一旦您确定了哪些XML产生了预期的效果(或者发现PowerPoint不允许您这样做),那么您可以继续研究如何获取python-pptx
生成的XML。如果你能够做到这一点,这可能会成为第二个问题。
答案 1 :(得分:0)
我通过编写以下代码使它起作用。
def apply_data_labels(self, chart):
plot = chart.plots[0]
plot.has_data_labels = True
for series in plot.series:
values = series.values
counter = 0
for point in series.points:
data_label = point.data_label
data_label.has_text_frame = True
data_label.text_frame.text = str(values[counter])
counter = counter + 1
答案 2 :(得分:0)
要补充Vibhanshu的响应,我可以使用以下代码来设置格式(字体类型,字体颜色,大小等):
for idx, point in enumerate(chart.series[0].points):
# set position
point.data_label.position = XL_LABEL_POSITION.OUTSIDE_END
# set text
point.data_label.has_text_frame = True
point.data_label.text_frame.text = "This is an example"
# set formatting
for paragraph_idx, paragraph in enumerate(point.data_label.text_frame.paragraphs):
paragraph.line_spacing = 0.6 # set paragraph line spacing
for run in paragraph.runs:
run.font.size = Pt(30) #set font size
run.font.name = 'Poppins Medium' #set font name
run.font.color.rgb = RGBColor.from_string("FF0000") #set font color