Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use XlsxWriter to plot a barchart and fill in different colors for each of the bar in the same series

Tags:

xlsxwriter

For example, I have 3 data elements (49, 23, 40 for example) for Jan, Feb and Mar , and they all belong to the same series 1. When I plot them in a bar chart, they can only be filled by the same color in XlsxWriter. What can I do to fill them with different colors? Thanks!

like image 428
whitneyli Avatar asked Nov 20 '25 05:11

whitneyli


1 Answers

In general in XlsxWriter (and Excel) you can set the colour for a bar chart using the line and/or fill properties.

To set the colour for each bar you need to set the colour for each point in the series. For example:

import xlsxwriter

workbook = xlsxwriter.Workbook('chart.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write_column('A1', ['Jan', 'Feb', 'Mar'])
worksheet.write_column('B1', [49,    23,     40])

chart = workbook.add_chart({'type': 'bar'})

chart.add_series({
    'categories': '=Sheet1!$A$1:$A$3',
    'values':     '=Sheet1!$B$1:$B$3',
    'points': [
        {'fill': {'color': 'red'}},
        {'fill': {'color': 'green'}},
        {'fill': {'color': 'blue'}},
    ],
})

worksheet.insert_chart('B5', chart)
workbook.close()

Output:

enter image description here

See the XlsxWriter documentation on chart series point options and Working with Colors.

like image 179
jmcnamara Avatar answered Nov 21 '25 22:11

jmcnamara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!