Search code examples
pythonexcelxlsxwriter

How to set invert_if_negative to fill bars to a solid color in python xlswriter


I am making graphics on excel from python using xls writer and want to make a graphic with green colored bars for positive values, and red for negative.

Current code seems like this:

chart3 = workbook.add_chart({'type': 'column'})
chart3.add_series({
    'values': '=Summary!$W$2:$W$76',
    'categories': '=Summary!$A$2:$A$76',
    'gap': 4,
    'line': {'width': 1},
    'name': '=Summary!$W$1',
    'fill':   {'color': 'green'},
    'invert_if_negative': True
})

It differientiates positive and negative values in the graph but the negative ones are just no-colored. Is there a way to make the inverted color to be red?

Already tried with other properties like inverted_color or any syntax like that but does not work


Solution

  • You will need version >= 3.1.1 of XlsxWriter which supports the invert_if_negative_color parameter:

    from xlsxwriter import Workbook
    
    
    workbook = Workbook("chart.xlsx")
    
    worksheet = workbook.add_worksheet()
    chart = workbook.add_chart({"type": "column"})
    
    worksheet.write_column("A1", [3, 2, -3, 4, -2])
    
    chart.add_series(
        {
            "values": "=Sheet1!$A$1:$A$5",
            "fill": {"color": "green"},
            "invert_if_negative": True,
            "invert_if_negative_color": "red",
        }
    )
    
    worksheet.insert_chart("C1", chart)
    
    workbook.close()
    
    

    Output:

    enter image description here