Python PPTX 条形图负值

Python PPTX Bar Chart negative values

对于由 python-pptx 生成的条形图,我使用以下代码为条形指定特定颜色。

chart.series[0].format.fill.solid()
chart.series[0].format.fill.fore_color.rgb = RGBColor(160,190,230)

大部分时间看起来都不错。但是,然后条形图有负值,条形图会出现几个问题。

我已经尝试了以下两个选项都没有效果。

chart.series[0].invert_if_negative = True
chart.series[0].invert_if_negative = False

有没有办法使图表正确呈现,有颜色且不与类别名称重叠?

嗯,这是两个问题。但就类别名称重叠而言,您可以通过将刻度标签位置设置为 LOW 来解决此问题:

from pptx.enum.chart import XL_TICK_LABEL_POSITION

category_axis = chart.category_axis
category_axis.tick_label_position = XL_TICK_LABEL_POSITION.LOW

在透明(或可能是白色)的彩色条上,我怀疑您可能看到了 PowerPoint 版本相关的不符合规范的问题,这种情况在其他地方出现过。我会在 PowerPoint 中打开它,看看您可以在属性对话框中看到什么,如果否定选项是否按照您设置的方式出现,以及当您使用 PowerPoint UI 手动设置它时它是否运行。

如果使用 python-pptx 将 "Invert if negative" 复选框设置为 True 并在“数据系列”>“填充(格式)”对话框中未选中该复选框并单击该复选框可解决显示问题,您可以在 python-pptx GitHub 问题列表中创建案例,我们将在下一个版本中修复。

基本上,某些版本的 PowerPoint 会根据元素 (<c:invertIfNegative> in this case) 不一致地解释诸如此类的布尔元素类型,因此虽然它通过了测试,但它在所有 PowerPoint 中的行为并不像预期的那样版本。这可能就是你所看到的。

尝试深入了解 xml:

    ccaxis = chart.category_axis
    ticklblPos = ccaxis._element.find('{http://schemas.openxmlformats.org/drawingml/2006/chart}tickLblPos')
    ticklblPos.set('val','low')

fill.patterned() 替换 fill.solid() 对我有用:

color_red = RGBColor(254, 98, 94)
color_green = RGBColor(1, 194, 170)

for idx, point in enumerate(series.points):
    fill = point.format.fill
    fill.patterned()
    if data[idx]<0 :
        fill.fore_color.rgb = color_red   
    else:
        fill.back_color.rgb = color_green