6

Is it possible in python-pptx to color a specific bar in a bar chart different from others? My intention is to color the bar based on values. By default, all is blue, but if the value is below certain threshold, the bar is colored red.

Below is my current code with all bars colored blue-ish, rgb(65,105,225)

 # HUMIDITY CHART
    chart_data = ChartData()              
    chart_data.categories = list(m.columns)

    chart_data.add_series('Humidity', list(m.loc[svc,'Humidity']), 3)
    graphic_frame = s.placeholders[14].insert_chart(XL_CHART_TYPE.COLUMN_CLUSTERED, chart_data)
    chart = graphic_frame.chart

    plot = chart.plots[0]
    plot.has_data_labels = True
    plot.overlap = 0
    plot.gap_width = 30
    data_labels = plot.data_labels
    data_labels.font.size = Pt(11)
    data_labels.font.color.rgb = RGBColor(0,0,0)
    data_labels.number_format = "#,##0"

    chart.series[0].fill.solid()
    chart.series[0].fill.fore_color.rgb = RGBColor(65,105,225)
idazuwaika
  • 2,749
  • 7
  • 38
  • 46

1 Answers1

7

I believe this will do the trick:

bar_idx = the_offset_of_the_bar_I_want_to_set_to_a_different_color
point = series.points[bar_idx]  # a (data) point in a bar chart is a bar
fill = point.format.fill
fill.solid()
fill.fore_color.rgb = RGBColor(65, 105, 225)

There's a gap in the documentation for series.points, which is why you probably didn't find this.

Let us know how you go :)

scanny
  • 26,423
  • 5
  • 54
  • 80
  • Thanks, but I received either AttributeError: 'BarSeries' object has no attribute 'points', or AttributeError: 'SeriesCollection' object has no attribute 'points' in my various tries. – idazuwaika Feb 12 '17 at 08:16
  • Tried both point = chart.series.points[bar_idx] and point = chart.series[0].points[bar_idx] – idazuwaika Feb 12 '17 at 08:18
  • What version of `python-pptx` are you using? Sounds like it's time for an upgrade. BarSeries should have a `.points` property. – scanny Feb 12 '17 at 19:00
  • Was using 0.5.8. Upgraded to 0.6.2 and solved the problem. Thanks! – idazuwaika Feb 14 '17 at 01:59
  • @scanny is there a point to change all the bars at the same time? `series = plot.series[0] point0 = series.points[0] #first bar point0_fill = point0.format.fill point0_fill.solid() point0_fill.fore_color.rgb = RGBColor(220, 192, 40) point1 = series.points[1] #second bar point1_fill = point1.format.fill point1_fill.solid() point1_fill.fore_color.rgb = RGBColor(220, 192, 40)` This is my solution, which is really redundant. – Zed Fang Jun 06 '18 at 07:22
  • @ZedFang Try `plot.series[0].format.fill`. I'm not sure it will work as PowerPoint is a little finicky about when it pays attention to more global settings like that. Otherwise just make a function or method to iterate through all the points and set their color. Ask a new question if you need more and tag with `python-pptx` tag. – scanny Jun 06 '18 at 16:13