简体   繁体   English

python-pptx - 如何在图形中单独隐藏/显示数据标签

[英]python-pptx – How to individually hide/show data labels in graph

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.我认为这可以通过访问单个数据标签来实现: plot.series[0].points[1].data_label然后将其has_text_frame属性分配给TrueFalse ,但这不起作用。

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.我相信 PowerPoint 支持这两种方法,但python-pptx将只支持“添加”方法,如果它这样做的话。

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"

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

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