Friday, 26 March 2021

Create barchart using openpyxl, with dates on x axis

I have a dataset where I would like to create a barchart (using openpyxl) with dates on the x axis, and cost on the y. The categories will be differentiated by color.

Data (already in excel)

Category 2021-01    2021-02
Network  10         20
Other    20         30
Storage  10         10
Compute  10         10
Total:   50         70

enter image description here

Desired

Something similar to this, with date being on the X axis

enter image description here

Is this possible, or would I have to change the layout of the data in excel?

Doing

path = "C:/Users/th/data.xlsx"
wb_obj = load_workbook(path)
sheet_obj = wb_obj.active

c1 = BarChart()
c1.title = "Global Costs"
c1.y_axis.title = "Cost in Dollars"
c1.x_axis.title = "Category"
c1.x_axis.number_format = 'mm/dd/yy'
c1.x_axis.majorTimeUnit = "days";
c1 = deepcopy(c1)
c1.style = 39


data = Reference(sheet_obj, min_col=2, min_row=9, max_col=3, max_row=14)
c1.add_data(data, titles_from_data=True)

cats = Reference(sheet_obj, min_col=1, max_col=1, min_row=10, max_row=13)
c1.set_categories(cats)



sheet_obj.add_chart(c1, "E9")
wb_obj.save("sample.xlsx")

Is this possible, or would I have to change the layout of the data in excel? Any suggestion is appreciated



from Create barchart using openpyxl, with dates on x axis

No comments:

Post a Comment